#!/usr/bin/env python2.7

import sys
import argparse
import traceback
import subprocess
from subprocess import check_output

debug_flag=True

def debug_msg(x):
    if debug_flag:
        print x

#import packageLookupTable
sys.path.extend(["/usr/share/volatile/lib","./lib"])
try:
    from packagetable import packageLookupTable
except Exception:
    debug_msg(traceback.format_exc())
    debug_msg("can't find packageLookupTable in /usr/share/volatile/lib")
    
import package_aptlib

def fetchPackages(aptoptions, **kwargs):
    debug_msg("aptInstall: Entering fetchPackages")

    fetch_pkgs = packageLookupTable.keys()

    taskdir = '';
    postGM = False
    for key, value in kwargs.iteritems():
        if key == 'post':
            postGM = True
	if key == 'task':
            taskdir = kwargs[key]
    if postGM:
        debug_msg("aptInstall: To fetch postGM packages.")
    else:
        debug_msg("aptInstall: To fetch normal packages in %s." %taskdir)
        rawpkgs = subprocess.check_output('/usr/share/volatile/generate-dpkg-list -k apt_install -k apt_install_oobe %s' %taskdir, shell=True)
        fetch_pkgs = rawpkgs.split()
    _option = "".join([aptoptions, " -o Dir::Cache::Archives=/usr/share/volatile/archives install -d --reinstall "])
    
    debug_msg("aptInstall: fetch_pkgs: %s" % fetch_pkgs)
    
    for p in fetch_pkgs:
        option = "".join(["apt-get ", _option, p])
        try:
            debug_msg("aptInstall: apt-get command %s" % option)
            subprocess.check_call(option, shell=True)
        except Exception:
            debug_msg(traceback.format_exc())
            debug_msg("aptInstall: Fail to fetch package %s" % p)

def aptInstall(aptoptions, pkgName, skuName):
    try:
        _option = "apt-get " + aptoptions + " " + pkgName
        if pkgName in packageLookupTable.keys():
            try:
                option = "".join([_option, "=", packageLookupTable[pkgName][skuName]])
            except Exception:
                debug_msg(traceback.format_exc())
                try:
                    option = "".join([_option, "=", packageLookupTable[pkgName]["lockDown"]])
                except Exception:
                    debug_msg(traceback.format_exc())
                    option = _option
        else:
            option = _option
        debug_msg("aptInstall: pkgName = %s, skuName = %s, apt-get command %s" %(pkgName, skuName, option))
        subprocess.check_call(option, shell=True)
        version = check_output("dpkg-query -W %s | awk '{print  $2}'" %pkgName, shell=True).split("\n")[0]
        with open("/var/log/volatile-task-apt-install-py.log","a+") as f:
            f.write("%s %s\n" %(pkgName, version))
    except Exception:
        debug_msg(traceback.format_exc())
        debug_msg("aptInstall: Fail to install the package %s for %s" %(pkgName, skuName))
        sys.exit()

def list_pkgs_name():
    for p in packageLookupTable.keys():
        print p

def main():

    parser = argparse.ArgumentParser(description='Fetch and install packages in volatile-task.')
    parser.add_argument('-o','--operation', type=str, default="apt_install",
                    help='Choose operation: apt_install fetch_pkgs fetch_pkgs_postgm list_pkgs_name install_packagefilelist')
    parser.add_argument('-a','--aptoption', type=str, default="--yes --allow-downgrades --allow-remove-essential --allow-unauthenticated install",
                    help='APT install options to be applied.')
    parser.add_argument('-p','--pkgname', type=str, default="",
                    help='Specify the package name to be fetched or installed')
    parser.add_argument('-s','--sku', type=str, default="",
                    help='Specify the sku name by verifying system ID.')
    parser.add_argument('-f','--packagefilelist', type=str, default="data/packageslist.txt",
                    help='Specify the package file list.')
    parser.add_argument('-T', '--task', dest='taskdir', default='/usr/share/volatile/task',
		    help='Specify the task directory' )
    parser.add_argument('--debug', action="store_true", default=False,
                    help='Debugging flag (default: False)')
    args = parser.parse_args()
    
    if args.debug == False:
        global debug_flag
        debug_flag=False

    if args.operation == "apt_install":
        if len(args.pkgname) == 0:
            debug_msg("Missing pkgname")
        else:
            aptInstall(args.aptoption, args.pkgname, args.sku)
    else:
        if args.operation == "fetch_pkgs":
            debug_msg("fetch_pkgs")
            fetchPackages(args.aptoption, task=args.taskdir)
        elif args.operation == "fetch_pkgs_postgm":
            debug_msg("fetch_pkgs_postgm")
            fetchPackages(args.aptoption, post=True, task=args.taskdir)
        elif args.operation == "list_pkgs_name":
            list_pkgs_name()
        elif args.operation == "install_packageslist":
            package_aptlib.install_packageslist(args.aptoption, args.packagefilelist,type="task-apt-install")
        elif args.operation == "install_packageslist_chroot":
            package_aptlib.install_packageslist(args.aptoption, args.packagefilelist,type="server-chroottask-apt-install")
        elif args.operation == "convert_packageslist_chroot":
            package_aptlib.convert_packageslist(args.aptoption, args.packagefilelist,type="server-chroottask-apt-install" )            
        elif args.operation == "verify_packageslist":
            package_aptlib.verify_packageslist(args.aptoption, args.packagefilelist)

if __name__ == "__main__":
    main()
