#!/bin/sh -e
#
# this script is part of Hets
# - Heterogenous Tool Set -
#

#
# Handling switches
#  -update
#  -revert
#
if [ "$#" = "1" ]; then
    case "$1" in

    -update)
        if [ "`id -u`" = "0" ]; then
            apt-get install hets-core
            export HETS_DAILY_VERSION=`date +%Y%m%d`
python << __END__
import fcntl, os, sys, subprocess;

subprocess.DEVNULL=os.open(os.devnull, os.O_RDWR)
subprocess.STDOUT=sys.stdout
subprocess.STDERR=sys.stderr

class UpdateFailure(Exception):
    def __init__(self, msg):
        self.value = msg
    def __str__(self):
        return repr(self.msg)

try:
    f = open("/var/lib/dpkg/lock", 'w')
    fcntl.lockf(f, fcntl.LOCK_EX|fcntl.LOCK_NB)
    print "Retrieving latest Hets library...",
    sys.stdout.flush()
    subprocess.call("rm -r -f /tmp/hets*",shell=True,stderr=subprocess.DEVNULL)
    try:
        subprocess.check_call(["git","clone", "-q", "--depth=50",
         "https://github.com/spechub/Hets-lib.git","/tmp/hets-lib"],
         stdout=subprocess.STDOUT,stderr=subprocess.STDERR)
    except subprocess.CalledProcessError:
        raise UpdateFailure("Failed to retrieve latest Hets library!")
    print "Done"
    print "Retrieving latest Hets binary...",
    sys.stdout.flush()
    try:
        if os.uname()[4] == "x86_64":
            subprocess.check_call("curl -sG http://www.informatik.uni-bremen.de/agbkb/forschung/formal_methods/CoFI/hets/linux64/daily/hets.bz2 \
                         > /tmp/hets-$HETS_DAILY_VERSION.bz2",shell=True,stdout=sys.stdout,stderr=sys.stderr)
        else:
            subprocess.check_call("curl -sG http://www.informatik.uni-bremen.de/agbkb/forschung/formal_methods/CoFI/hets/linux/daily/hets.bz2 \
                         > /tmp/hets-$HETS_DAILY_VERSION.bz2",shell=True,stdout=sys.stdout,stderr=sys.stderr)
    except subprocess.CalledProcessError:
        raise UpdateFailure("Failed to retrieve latest Hets binary...")
    try:
        subprocess.check_call(["bunzip2", "/tmp/hets-$HETS_DAILY_VERSION.bz2"],
         stdout=subprocess.STDOUT,stderr=subprocess.STDERR)
        subprocess.call(["chmod","+x","/tmp/hets-$HETS_DAILY_VERSION"])
        subprocess.check_call(["/tmp/hets-$HETS_DAILY_VERSION","-V"],
         stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    except subprocess.CalledProcessError:
        raise UpdateFailure("Retrieved Hets binary seems broken. Please try again later!")
    print "Done"
    print "Retrieving latest hets.magic file...",
    sys.stdout.flush()
    try:
        subprocess.check_call("curl -sG http://www.informatik.uni-bremen.de/agbkb/forschung/formal_methods/CoFI/hets/src-distribution/hets.magic \
                         > /tmp/hets.magic",shell=True,stdout=sys.stdout,stderr=sys.stderr)
    except subprocess.CalledProcessError:
        raise UpdateFailure("Failed to retrieve hets.magic!")
    print "Done"
    print "Retrieving latest Hets OWL2Parser.jar...",
    sys.stdout.flush()
    subprocess.call("rm -r -f /tmp/OWL2Parser.jar",shell=True,stderr=subprocess.DEVNULL)
    try:
        subprocess.check_call("curl -sG http://www.informatik.uni-bremen.de/agbkb/forschung/formal_methods/CoFI/hets/src-distribution/OWL2Parser.jar \
                         > /tmp/OWL2Parser.jar",shell=True,stdout=sys.stdout,stderr=sys.stderr)
    except subprocess.CalledProcessError:
        raise UpdateFailure("Failed to retrieve Hets OWL2Parser.jar!")
    print "Done"
    print "Creating Backups ...",
    sys.stdout.flush()
    try:
        subprocess.check_call(["mv", "/usr/lib/hets/hets.magic",
         "/usr/lib/hets/hets.magic.bak"],stderr=subprocess.DEVNULL)
        subprocess.check_call(["mv", "/usr/lib/hets/hets-owl-tools/OWL2Parser.jar",
         "/usr/lib/hets/hets-owl-tools/OWL2Parser.jar.bak"],stderr=subprocess.DEVNULL)
        subprocess.check_call(["mv", "/usr/lib/hets/hets",
         "/usr/lib/hets/hets.bak"],stderr=subprocess.DEVNULL)
        subprocess.check_call(["rm", "-r", "-f", "/usr/lib/hets/hets-lib.bak"],stderr=subprocess.DEVNULL)
        subprocess.check_call(["mv","/usr/lib/hets/hets-lib",
         "/usr/lib/hets/hets-lib.bak"],stderr=subprocess.DEVNULL)
    except subprocess.CalledProcessError:
        raise UpdateFailure ("Couldn't create backups. Please make sure the package hets-core is properly installed!")
    print "Done"
    print "Installing new files ...",
    sys.stdout.flush()
    try:
        subprocess.check_call(["install", "-m", "755", "/tmp/hets-$HETS_DAILY_VERSION",
                               "/usr/lib/hets/hets"],stderr=subprocess.DEVNULL)
        subprocess.check_call(["cp", "-r", "/tmp/hets-lib", "/usr/lib/hets/hets-lib"])
        subprocess.check_call(["install", "-m", "644", "/tmp/OWL2Parser.jar",
                               "/usr/lib/hets/hets-owl-tools/"],stderr=subprocess.DEVNULL)
        subprocess.check_call(["install", "-m", "644", "/tmp/hets.magic",
                               "/usr/lib/hets/"],stderr=subprocess.DEVNULL)
    except subprocess.CalledProcessError:
         print "Installation possibly incomplete please try again later or revert"
    print "Done"
except IOError:
    print "Could not acquire lock \"/var/lib/dpkg/lock\""
    sys.exit(0)
except UpdateFailure as e:
    print "Experienced update failure: ", e.value
finally:
    if not os.path.exists("/usr/lib/hets/hets-lib"):
      subprocess.call(["mv","/usr/lib/hets/hets-lib.bak","/usr/lib/hets/hets-lib"],stderr=subprocess.DEVNULL)
    if not os.path.exists("/usr/lib/hets/hets"):
      subprocess.call(["mv","/usr/lib/hets/hets.bak","/usr/lib/hets/hets"],stderr=subprocess.DEVNULL)
    if not os.path.exists("/usr/lib/hets/hets-owl-tools/OWL2Parser.jar"):
      subprocess.call(["mv","/usr/lib/hets/hets-owl-tools/OWL2Parser.jar.bak",
           "/usr/lib/hets/hets-owl-tools/OWL2Parser.jar"],stderr=subprocess.DEVNULL)
    if not os.path.exists("/usr/lib/hets/hets.magic"):
      subprocess.call(["mv","/usr/lib/hets/hets.magic.bak",
           "/usr/lib/hets/hets.magic"],stderr=subprocess.DEVNULL)
    subprocess.call("rm -r -f /tmp/hets*",shell=True,stderr=subprocess.DEVNULL)
    subprocess.call("rm -r -f /tmp/OWL2Parser.jar",shell=True,stderr=subprocess.DEVNULL)
    sys.exit(0)
__END__
            echo "Updated to `hets -V`."
            exit 0
        else
            echo "Root access required for \"hets -update\""
            exit 0
        fi
    ;;

    -revert)
        if [ "`id -u`" = "0" ]; then
            if [ -f /usr/lib/hets/hets.bak ]; then
python << __END__
import fcntl, os, sys, subprocess;

subprocess.DEVNULL=os.open(os.devnull, os.O_RDWR)
subprocess.STDOUT=sys.stdout
subprocess.STDERR=sys.stderr

class UpdateFailure(Exception):
    def __init__(self, msg):
        self.value = msg
    def __str__(self):
        return repr(self.msg)

try:
    f = open("/var/lib/dpkg/lock", 'w')
    fcntl.lockf(f, fcntl.LOCK_EX|fcntl.LOCK_NB)
    print "Reverting to previous Hets binary... ",
    try:
        subprocess.check_call(["mv", "/usr/lib/hets/hets.bak",
         "/usr/lib/hets/hets"],stderr=subprocess.DEVNULL);
        if os.path.exists("/usr/lib/hets/hets.magic.bak"):
           subprocess.check_call(["mv", "/usr/lib/hets/hets.magic.bak",
            "/usr/lib/hets/hets.magic"],stderr=subprocess.DEVNULL);
        if os.path.exists("/usr/lib/hets/hets-owl-tools/OWL2Parser.jar.bak"):
           subprocess.check_call(["mv", "/usr/lib/hets/hets-owl-tools/OWL2Parser.jar.bak",
            "/usr/lib/hets/hets-owl-tools/OWL2Parser.jar"],stderr=subprocess.DEVNULL);
        if os.path.exists("/usr/lib/hets/hets-lib.bak"):
           subprocess.check_call(["rm", "-r", "-f", "/usr/lib/hets/hets-lib"],
            stderr=subprocess.DEVNULL)
           subprocess.check_call(["mv", "/usr/lib/hets/hets-lib.bak",
            "/usr/lib/hets/hets-lib"],stderr=subprocess.DEVNULL)
    except subprocess.CalledProcessError:
        raise UpdateFailure("Couldn't restore backup!")
    print "Done"
except IOError:
    print "Could not acquire lock \"/var/lib/dpkg/lock\""
    sys.exit(0)
except UpdateFailure as e:
    print "Experienced revert failure: ", e.value
sys.exit(0)
__END__
                echo "Reverted to `hets -V`."
                exit 0
            else
                echo "No hets.bak found to revert."
                exit 0
            fi
        else
            echo "Root access required for \"hets -revert\""
            exit 0
        fi
    esac
fi

#
# Setting environment variables
# and starting Hets
#

export HETS_MAGIC=/usr/lib/hets/hets.magic
export HETS_LIB=/usr/lib/hets/hets-lib
export HETS_OWL_TOOLS=/usr/lib/hets/hets-owl-tools
export HETS_ISABELLE_LIB=/usr/lib/hets/hets-lib/Isabelle
export HETS_ISA_TOOLS=/usr/lib/hets/hets-isa-tools
export HETS_APROVE=$HETS_OWL_TOOLS/AProVE.jar
export HETS_ONTODMU=$HETS_OWL_TOOLS/OntoDMU.jar
export HETS_MAUDE_LIB=/usr/lib/hets/hets-maude-lib
export HETS_HOLLIGHT_TOOLS=/usr/lib/hets/hets-hollight-tools
export HETS_HOL_DIR=/usr/share/hol-light
export HETS_OCAML_LIB_DIR=/usr/lib/ocaml/compiler-libs
export PELLET_PATH=/usr/share/pellet
export TWELF_LIB=/usr/share/twelf/bin
export MAUDE_LIB=/usr/share/maude

exec /usr/lib/hets/hets ${1+"$@"}
