#!/bin/env python3
# -*- coding: utf-8 -*-

### https://apt-team.pages.debian.net/python-apt/library/index.html

import os
import apt
import apt_pkg
import sys  

def upgrade_specific_version(package_name, fix_version):
    # 初始化APT软件包管理器  
    apt_pkg.init()

    # 获取APT缓存
    cache = apt.Cache()

    # 更新APT缓存  
    #cache.update()

    # 获取指定名称的软件包  
    package = cache[package_name]

    # 检查软件包是否存在  
    if not package:
        print(f"Package '{package_name}' not found.")
        return
    print ("have package")

    # 获取当前包版本
    current_version = package.installed.version
    print ("cur verison ", current_version)

    # 获取软件包的版本列表  
    versions = package.versions

    # 检查指定版本是否存在  
    if fix_version not in versions:
        print(f"Version '{version}' of package '{package_name}' not found.")
        return
    print ("cache have version: ", fix_version)


    if (apt_pkg.version_compare(current_version, fix_version) < 0):
        print ("need update")
    else:
        print ("no need update")
        return


    # 设置软件包的安装版本
    #package.mark_install(fix_version)
    package.mark_install()
    
    # 执行升级操作
    try:
         cache.commit(fetch_progress=apt.progress.base.AcquireProgress(),  
                     install_progress=apt.progress.base.InstallProgress())
    except apt.transaction.Error as e:
        print(f"Error upgrading package '{package_name}': {str(e)}")
    else:
        print ("update package success");
        return 0

if __name__ == "__main__":
    print (sys.argv[1])
    package_name=""
    version=""
    inputstrs=sys.argv[1]
    parmstrs= inputstrs.split("###")
    for parmstr in parmstrs:
        if ">=" in parmstr:
            package_name=parmstr.split("(>=")[0]
            num_str = parmstr.split("(>=")[1]
            version=num_str[:-1]
            print("package:",package_name,"version:",version)
            upgrade_specific_version(package_name, version)
            pass
        elif "=" in parmstr:
            package_name=parmstr.split("(>=")[0]
            num_str = parmstr.split("(=")[1]
            version=num_str[:-1]
            print("package:",package_name,"version:",version)
            upgrade_specific_version(package_name, version)
            pass
