#!/usr/bin/python3

import sys
import os
import subprocess
import shlex

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("  autopurge        - Remove packages with their configuration files and automatically remove all unused packages")
    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("  showsrc          - Display all the source package records that match the given package name")
    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 = sys.argv[2:]

for command in ["install", "remove", "update", "clean"]:
    if argcommand.startswith("-") and command in argoptions:
            for i in range(0, len(argoptions)):
                if argoptions[i] == command:
                    argoptions[i] = argcommand
                    argcommand = command
                    break

command = ""

show_help = False
sort = False
highlight = False

if sys.stdin.isatty():
    rows, columns = os.popen('stty size', 'r').read().split()
else:
    rows, columns = '24', '80'

if argcommand == "help":
    if len(sys.argv) < 3:
        usage()
    show_help = True
    argcommand = sys.argv[2]
    argoptions = 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", "showsrc", "autopurge"):
    # apt
    command = ["/usr/bin/apt", argcommand] + argoptions
elif argcommand in ("clean", "dselect-upgrade", "build-dep", "check", "autoclean", "source", "moo"):
    # apt-get
    command = ["apt-get", argcommand] + argoptions
elif argcommand in ("reinstall", ):
    # aptitude
    command = ["aptitude", argcommand] + argoptions
elif argcommand in ("stats", "depends", "rdepends", "policy"):
    # apt-cache
    command = ["apt-cache", argcommand] + argoptions
elif argcommand in ("changelog", ):
    if os.path.exists("/usr/lib/python3/dist-packages/mintcommon/apt_changelog.py"):
        command = ["/usr/lib/python3/dist-packages/mintcommon/apt_changelog.py"] + argoptions
    else:
        command = ["aptitude", 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", argcommand] + argoptions
elif argcommand in ("markauto", "markmanual"):
    # apt-mark
    command = ["apt-mark", argcommand[4:]] + argoptions
elif argcommand == "contains":
    command = ["dpkg", "-S"] + argoptions
elif argcommand == "content":
    command = ["dpkg", "-L"] + argoptions
elif argcommand == "deb":
    command = ["dpkg", "-i"] + argoptions
elif argcommand == "build":
    command = ["dpkg-buildpackage"] + argoptions
elif argcommand == "version":
    command = ["dpkg-buildpackage"] + argoptions
    try:
        version = subprocess.check_output("dpkg-query -f '${Version}' -W %s 2>/dev/null" % shlex.quote(" ".join(argoptions)), shell=True).decode("UTF-8")
        print (version)
    except:
        print ("")
    sys.exit(0)
elif argcommand == "download":
    command = ["/usr/lib/linuxmint/mintsystem/mint-apt-download.py"] + argoptions
elif argcommand == "add-repository":
    command = ["add-apt-repository"] + argoptions
elif argcommand == "search":
    command = ["aptitude", "-w", columns, argcommand] + 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", "markauto", "markmanual", "autopurge"):
    command = ["sudo"] + command

# Color highlighting
if argcommand in ("content", "version", "policy", "depends", "rdepends", "search") and len(argoptions) >= 1:
    highlight = True

# Sorting
if argcommand in ("content", "contains"):
    sort = True

if show_help:
    print("\"apt " + argcommand + " " + " ".join(argoptions) + "\" is equivalent to \"" + " ".join(command) + "\"")
else:
    try:
        if sort and highlight:
            ps1 = subprocess.Popen(command, stdout=subprocess.PIPE)
            ps2 = subprocess.Popen("sort", stdin=ps1.stdout, stdout=subprocess.PIPE)
            ps3 = subprocess.Popen(["highlight-mint"] + argoptions, stdin=ps2.stdout)
            ps3.wait()
        elif sort:
            ps1 = subprocess.Popen(command, stdout=subprocess.PIPE)
            ps2 = subprocess.Popen("sort", stdin=ps1.stdout)
            ps2.wait()
        elif highlight:
            ps1 = subprocess.Popen(command, stdout=subprocess.PIPE)
            ps2 = subprocess.Popen(["highlight-mint"] + argoptions, stdin=ps1.stdout)
            ps2.wait()
        else:
            return_code = subprocess.call(command)
            sys.exit(return_code)
    except KeyboardInterrupt:
        print()
