#!/usr/bin/env python3

import gi
import traceback
import os
import sys

gi.require_version('OSTree', '1.0')
from gi.repository import GLib, Gio, OSTree, GObject

# 指定文件路径
file_path = "/ostree/pkgs/ostree-version.info"

def main():
    try:
        # 初始化 OSTree.Sysroot
        sysroot = OSTree.Sysroot.new(None)
        sysroot.set_mount_namespace_in_use()
        sysroot.initialize()
        sysroot.load()

        # 获取部署列表
        deployment_list = sysroot.get_deployments()
        if not deployment_list:
            print("No deployments found.")
            return

        # 遍历部署列表
        result = None
        for deployment in deployment_list:
            if not deployment.is_pinned():
                csum = deployment.get_csum()
                osname = deployment.get_osname()
                deployserial = deployment.get_deployserial()
                result = f"{osname} {csum}.{deployserial}"
                break

        if result is None:
            print("No unpinned deployment found.")
            return

        # 写入文件
        try:
            with open(file_path, 'w') as file:
                file.write(result)
            print(f"Successfully wrote '{result}' to {file_path}")
        except PermissionError:
            print(f"Permission denied when trying to write to {file_path}. Try running the script with sudo.")
        except Exception as e:
            print(f"An error occurred while writing to file: {e}")

    except GLib.Error as e:
        print(f"GLib.Error occurred: {e}")
    except ImportError as e:
        print(f"ImportError occurred: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        traceback.print_exc()

if __name__ == "__main__":
    main()
