#!/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
from pathlib import Path

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)

# 3. 备份成功时创建还原标识文件
if settings.get("current_update", {}).get("backup_success", True):
    flag_path = Path(RESTORE_FLAG_FILE)

    # 确保父目录存在
    flag_path.parent.mkdir(parents=True, exist_ok=True)

    # 写入标志文件
    flag_path.write_text("restore flag created for update service\n", encoding="utf-8")

    print(f"Created restore flag file: {flag_path}")
