#!/usr/bin/python3
import os
import subprocess
import sys

from pearlcommon import synaptic

if __name__ == "__main__":
    if not os.getuid() == 0:
        print("E: pearl-refresh-cache requires root privileges")
        sys.exit(1)

    update_error = True

    if len(sys.argv) > 2 and sys.argv[1] == "--use-synaptic":
        update_error = synaptic.update_cache(sys.argv[2])
        if update_error:
            print(f"E: Synaptic returned error code {update_error}")
    else:
        import apt
        cache = apt.Cache()
        try:
            cache.update()
            update_error = False
        except apt.cache.FetchFailedException as e:
            # Repository unavailable, either server down or apt is misconfigured
            print(e)
        except:
            import traceback
            traceback.print_exc()

    if "--pearlinstall" in sys.argv[1:]:
        if not update_error and os.path.exists("/usr/bin/pearlinstall-update-pkgcache"):
            # Run the pearlinstall cache update asynchronously
            try:
                subprocess.Popen(["/usr/bin/pearlinstall-update-pkgcache"])
            except:
                pass

    if "--pearlupdate" in sys.argv[1:]:
        # Mainline kernel PPA support
        sys.path.append("/usr/lib/pearllinux/pearlUpdate")
        from common.constants import USE_MAINLINE_KERNELS

        if USE_MAINLINE_KERNELS:
            from common.MainlineKernels import MainlineKernels

            mainline = MainlineKernels(cached=False)
            try:
                mainline_kernels = mainline.get_available_versions()
                mainline_kernels = mainline.get_support_status()
            except:
                pass
