#! /usr/bin/env python
# (c) Copyright 2012. CodeWeavers, Inc.

import os

# Portable which(1) implementation
def which(path, app):
    """Looks for an executable in the specified directory list.

    path is an os.pathsep-separated list of directories and app is the
    executable name. If app contains a path separator then path is ignored.
    If the file is not found, then None is returned.
    """
    if os.path.isabs(app):
        if os.path.isfile(app) and os.access(app, os.X_OK):
            return app
    elif os.sep in app or (os.altsep and os.altsep in app):
        app_path = os.path.join(os.getcwd(), app)
        if os.path.isfile(app_path) and os.access(app_path, os.X_OK):
            return app_path
    else:
        for directory in path.split(os.pathsep):
            if directory == "":
                continue
            app_path = os.path.join(directory, app)
            if os.path.isfile(app_path) and os.access(app_path, os.X_OK):
                return app_path
    return None

import sys
def locate_cx_root():
    """Locate where CrossOver is installed.

    We start by locating our own python script file and walking back up the
    path, traversing symbolic links on the way. Then we verify what we have
    found the right directory by checking for the presence of the cxmenu
    script.
    """
    # pylint: disable-msg=I0011,W0601,W0603
    global CX_ROOT
    if "CX_DEVELOP_ROOT" in os.environ:
        CX_ROOT = os.environ["CX_DEVELOP_ROOT"]
        return

    # figure out argv0
    argv0 = which(os.environ["PATH"], sys.argv[0])
    if not argv0:
        argv0 = sys.argv[0]
        if not os.path.isabs(argv0):
            argv0 = os.path.join(os.getcwd(), argv0)

    # traverse the symbolic links
    dir0 = os.path.dirname(argv0)
    while True:
        if dir0.endswith("/lib"):
            bindir = dir0[0:-3] + "bin"
        else:
            bindir = dir0
        landmark = os.path.join(bindir, "cxmenu")
        if os.path.isfile(landmark):
            break
        if not os.path.islink(argv0):
            break
        argv0 = os.readlink(argv0)
        if not os.path.isabs(argv0):
            argv0 = os.path.join(dir0, argv0)
        dir0 = os.path.dirname(argv0)

    # compute CX_ROOT
    CX_ROOT = os.path.dirname(os.path.normpath(bindir))

    # check CX_ROOT
    landmark = os.path.join(CX_ROOT, "bin", "cxmenu")
    if not os.path.isfile(landmark) or not os.access(landmark, os.X_OK):
        sys.stderr.write("%s:error: could not find CrossOver in '%s'\n" % (os.path.dirname(sys.argv[0]), CX_ROOT))
        sys.exit(1)

    sys.path.append(os.path.join(CX_ROOT, "lib", "python"))

locate_cx_root()
import cxutils
cxutils.CX_ROOT = CX_ROOT


import shutil
import subprocess
import os
import distversion
import cxconfig
import time

def main():

    license_dir = os.path.join(os.environ['CX_ROOT'], "etc")
    license_file = os.path.join(license_dir, "license.txt")
    sig_file = os.path.join(license_dir, "license.sig")

    (isDemo, _username, _date, _licenseid, _revoked) = demo_status(license_file, sig_file)
    if isDemo:
        lameduck_license_file = os.path.join(license_dir, "lameducklicense.txt")
        lameduck_sig_file = os.path.join(license_dir, "lameducklicense.sig")

        shutil.move(lameduck_license_file, license_file)
        shutil.move(lameduck_sig_file, sig_file)
        

def demo_status(licenseFile, sigFile):
    """Checks the demo-status of the install.  Returns a 5-tuple.
       The first item is a simple boolean:  True if we're in demo
       mode, False if we aren't.  The second item is a string which
       will describe the account used to register the demo, if any.
       The third entry is the expiration date of the license.
       Fourth entry:  License ID
       Fifth entry:  True if this license has been revoked
    """

    keyFile = os.path.join(os.environ['CX_ROOT'], "share/crossover/data", "tie.pub")

    if not (os.path.exists(licenseFile) and os.path.exists(sigFile)):
        return (True, None, None, None, False)

    if not signatureIsValid(licenseFile, sigFile, keyFile):
        return (True, None, None, None, False)

    licenseData = cxconfig.get(licenseFile)
    username = licenseData[distversion.DEMO_SKU].get('customer')
    expiration = licenseData[distversion.DEMO_SKU].get('expires')
    licenseID = licenseData["license"].get('id')

    if not expiration or not username or not licenseID:
        # The license file is there, but there's no entry for this product.
        return (True, None, None, None, False)

    builddate = time.strptime(distversion.DATE,"%Y/%m/%d")
    expirationdate = time.strptime(expiration,"%Y/%m/%d")

    if builddate > expirationdate:
        return (True, username, expiration, licenseID, False)
    else:
        return (False, username, expiration, licenseID, False)


def signatureIsValid(fileName, sigFileName, keyFileName):
    args = ["openssl", "dgst", "-sha1", "-verify", keyFileName, "-signature", sigFileName, fileName]
    verification_result = subprocess.call(args)
    if verification_result == 0:
        return True
    else:
        return False


if __name__ == "__main__":
    sys.exit(main())
