#!/usr/bin/python3
# /*
#  * Copyright (C) 2020, KylinSoft Co., Ltd.
#  *
#  * This program is free software: you can redistribute it and/or modify
#  * it under the terms of the GNU General Public License as published by
#  * the Free Software Foundation, either version 3 of the License, or
#  * (at your option) any later version.
#  *
#  * This program is distributed in the hope that it will be useful,
#  * but WITHOUT ANY WARRANTY; without even the implied warranty of
#  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  * GNU General Public License for more details.
#  *
#  * You should have received a copy of the GNU General Public License
#  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
#  */
import os
import json
import sys

UPDATE_SETTINGS = "/var/cache/kylin-system-updater/settings.json"
RESTORE_FLAG_FILE = "/data/.backup/update-roolback"

# 1. 检查设置文件是否存在
if not os.path.exists(UPDATE_SETTINGS):
    print(f"Settings file does not exist: {UPDATE_SETTINGS}")
    sys.exit(0)

# 2. 尝试加载 JSON 设置
try:
    with open(UPDATE_SETTINGS, 'r') as f:
        settings = json.load(f)
except Exception as e:
    print(f"Failed to load update settings: {e}")
    sys.exit(0)

history = settings.get("history",[])
first_item = next(iter(history), {})
if first_item and first_item.get("success",True) and first_item.get("backup_success",True):
    print("Last deployment was successful, no need to remove restore flag.")
    if os.path.exists(RESTORE_FLAG_FILE):
        os.remove(RESTORE_FLAG_FILE)
        print(f"Removed restore flag file: {RESTORE_FLAG_FILE}")
