#!/usr/bin/python2 -O
import sys, os
# this avoids causing pid issues while checking for locks
os.environ['ETP_NO_PID_HANDLING'] = "1"
try:
    from entropy.const import etpConst
    package_file_ext = etpConst['packagesext']
    web_install_ext = etpConst['packagesext_webinstall']
except ImportError:
    package_file_ext = ".tbz2"
    web_install_ext = ".etp"
del os.environ['ETP_NO_PID_HANDLING']

kdesu_args = []
if "--debug" in sys.argv:
    kdesu_args.append("--debug")
    os.environ['SULFUR_DEBUG'] = "1"
    sys.argv.remove("--debug")

args = sys.argv[1:]
sulfur_path = "/usr/lib/entropy/sulfur/sulfur_client.py"
if args:
    sulfur_path += " " + " ".join(args)
su_cmd = "xterm -e \"su -c '" + sulfur_path + "'\""

def setup_env():
    global sulfur_path, su_cmd
    pathenv = os.getenv("PATH")
    if os.path.isfile("/etc/profile.env"):
        f = open("/etc/profile.env")
        env_file = f.readlines()
        for line in env_file:
            line = line.strip()
            if line.startswith("export PATH='"):
                line = line[len("export PATH='"):]
                line = line.rstrip("'")
                for path in line.split(":"):
                    pathenv += ":"+path
                break

    os.environ['PATH'] = pathenv

    de_session = os.getenv('DESKTOP_SESSION')
    kde_session = os.getenv('KDE_FULL_SESSION')
    if de_session == None: de_session = ''
    path = os.getenv('PATH').split(":")
    if (de_session.lower().find("kde") != -1) or kde_session:
        for item in path:
            itempath = os.path.join(item, 'kdesu')
            if os.access(itempath,os.X_OK):
                su_cmd = itempath + ' -t -- ' + sulfur_path + " " + \
                    " ".join(kdesu_args)
                break
    else:
        if os.access('/usr/bin/gksu', os.X_OK):
            su_cmd = '/usr/bin/gksu "' + sulfur_path + '"'



setup_env()
tbz2s = [x for x in sys.argv[1:] if (x.endswith(package_file_ext) or \
    x.endswith(web_install_ext))]
if tbz2s:
    os.environ['SULFUR_PACKAGES'] = ';'.join(tbz2s)
rc = 99
while rc in (99, 98):

    if rc == 98:
        os.environ['SULFUR_SYS_UPDATE'] = "1"
    elif os.getenv("SULFUR_SYS_UPDATE"):
        del os.environ['SULFUR_SYS_UPDATE']

    if os.getuid() == 0:
        rc = os.system(sulfur_path)
    else:
        rc = os.system(su_cmd)

raise SystemExit(rc)
