#!/usr/bin/python3

import sys
import os


def usage():
    print("apt")
    print("Usage: apt command [options]")
    print("       apt help command [options]")
    print("")
    print("Commands:")
    print("  add-repository   - Add entries to apt sources.list")
    print("  autoclean        - Erase old downloaded archive files")
    print("  autoremove       - Remove automatically all unused packages")
    print("  build            - Build binary or source packages from sources")
    print("  build-dep        - Configure build-dependencies for source packages")
    print("  changelog        - View a package's changelog")
    print("  check            - Verify that there are no broken dependencies")
    print("  clean            - Erase downloaded archive files")
    print("  contains         - List packages containing a file")
    print("  content          - List files contained in a package")
    print("  deb              - Install a .deb package")
    print("  depends          - Show raw dependency information for a package")
    print("  dist-upgrade     - Upgrade the system by removing/installing/upgrading packages")
    print("  download         - Download the .deb file for a package")
    print("  edit-sources     - Edit /etc/apt/sources.list with your preferred text editor")
    print("  dselect-upgrade  - Follow dselect selections")
    print("  full-upgrade     - Same as 'dist-upgrade'")
    print("  held             - List all held packages")
    print("  help             - Show help for a command")
    print("  hold             - Hold a package")
    print("  install          - Install/upgrade packages")
    print("  list             - List packages based on package names")
    print("  policy           - Show policy settings")
    print("  purge            - Remove packages and their configuration files")
    print("  recommends       - List missing recommended packages for a particular package")
    print("  rdepends         - Show reverse dependency information for a package")
    print("  reinstall        - Download and (possibly) reinstall a currently installed package")
    print("  remove           - Remove packages")
    print("  search           - Search for a package by name and/or expression")
    print("  show             - Display detailed information about a package")
    print("  showhold         - Same as 'held'")
    print("  source           - Download source archives")
    print("  sources          - Same as 'edit-sources'")
    print("  unhold           - Unhold a package")
    print("  update           - Download lists of new/upgradable packages")
    print("  upgrade          - Perform a safe upgrade")
    print("  version          - Show the installed version of a package")
    print("")
    sys.exit(1)

aliases = {
    "dist-upgrade": "full-upgrade",
    "sources": "edit-sources",
    "held": "showhold"
}

if len(sys.argv) < 2:
    usage()

argcommand = sys.argv[1]
argoptions = " ".join(sys.argv[2:])

command = ""

show_help = False

if argcommand == "help":
    if len(sys.argv) < 3:
        usage()
    show_help = True
    argcommand = sys.argv[2]
    argoptions = " ".join(sys.argv[3:])

if argcommand in aliases.keys():
    argcommand = aliases[argcommand]

if argcommand in ("autoremove", "list", "show", "install", "remove", "purge", "update", "upgrade", "full-upgrade", "edit-sources"):
    # apt
    command = "/usr/bin/apt %s %s" % (argcommand, argoptions)
elif argcommand in ("clean", "dselect-upgrade", "build-dep", "check", "autoclean", "source", "moo"):
    # apt-get
    command = "apt-get %s %s" % (argcommand, argoptions)
elif argcommand in ("search", "changelog", "reinstall"):
    # aptitude
    command = "aptitude %s %s" % (argcommand, argoptions)
elif argcommand in ("stats", "depends", "rdepends", "policy"):
    # apt-cache
    command = "apt-cache %s %s" % (argcommand, argoptions)
elif argcommand in ("recommends"):
    command = "/usr/lib/linuxmint/mintsystem/mint-apt-recommends.py " + argoptions
elif argcommand in ("showhold", "hold", "unhold"):
    # apt-mark
    command = "apt-mark %s %s" % (argcommand, argoptions)
elif argcommand == "contains":
    command = "dpkg -S %s | sort" % argoptions
elif argcommand == "content":
    command = "dpkg -L %s | sort" % argoptions
elif argcommand == "deb":
    command = "dpkg -i %s" % argoptions
elif argcommand == "build":
    command = "dpkg-buildpackage %s" % argoptions
elif argcommand == "version":
    command = "/usr/lib/linuxmint/common/version.py %s" % argoptions
elif argcommand == "download":
    archive_name = argoptions.split()[0]
    command = "apt update; "\
    "mkdir -p %(archive_name)s && "\
    "cd %(archive_name)s && "\
    "rm -rf *.deb && "\
    "LC_ALL=C apt-get install --dry-run %(argoptions)s | grep ^Inst | awk {'print $2;'} | xargs aptitude download -r && "\
    "echo 'sudo dpkg -i *.deb' > install.sh && "\
    "chmod a+rx install.sh && "\
    "cd .. && "\
    "tar cvf %(archive_name)s.tar %(archive_name)s/ >/dev/null && "\
    "gzip %(archive_name)s.tar && "\
    "rm -rf '%(archive_name)s' && "\
    "echo '\nThe packages were downloaded into %(archive_name)s.tgz. This archive contains all the packages necessary for an offline installation.\n'" \
    % {'archive_name':archive_name, 'argoptions':argoptions}
elif argcommand == "add-repository":
    command = "add-apt-repository %s" % argoptions
else:
    usage()
    sys.exit(1)

# Sudo prefix
if os.getuid() != 0 and argcommand in ("autoremove", "install", "remove", "purge", "update", "upgrade", "full-upgrade", "edit-sources", "clean", "dselect-upgrade", "build-dep", "check", "autoclean", "reinstall", "deb", "hold", "unhold", "add-repository"):
    command = "sudo %s" % command

# Color highlighting
if argcommand in ("content", "version", "policy", "depends", "rdepends") and len(argoptions.strip()) > 1:
    command = "%s | highlight %s" % (command, argoptions)

if show_help:
    print("\"apt " + argcommand + " " + argoptions + "\" is equivalent to \"" + command + "\"")
else:
    os.system(command)
