#!/usr/bin/python3

import os
import sys

import toaru_package

if __name__ == "__main__":

    if not os.getuid() == 0:
        print(f"{sys.argv[0]}: must be root")
        sys.exit(1)

    toaru_package.fetch_manifest()

    if len(sys.argv) < 2:
        print("Available packages:")
        packages = sorted(toaru_package.manifest['packages'].keys())
        for k in packages:
            print(f" - {k}","(installed)" if k in toaru_package.installed_packages else "")
        sys.exit(0)

    for arg in sys.argv[1:]:
        if arg.startswith("--"):
            if arg == "--dryrun":
                toaru_package.dryrun = True
                print("(Simulating installation.)")
            if arg == "--gui":
                toaru_package.is_gui = True
        else:
            toaru_package.process_package(arg)

    toaru_package.calculate_upgrades()

    for package in toaru_package.packages_to_install:
        if package in toaru_package.upgrade_packages:
            print(f"Upgrading {package}...")
            toaru_package.install_package(package)
        elif package in toaru_package.install_packages:
            print(f"Installing {package}...")
            toaru_package.install_package(package)

    if not toaru_package.upgrade_packages and not toaru_package.install_packages:
        print(f"{sys.argv[0]}: up to date")

    toaru_package.write_status()
