#!/bin/bash
{
    #
    # Last updated 26 Jan 2021
    #

    RET=0
    RPM=0
    DEB=0
    YES=0
    TGZ=0
    CMDLINEFILE=0
    ALTURL=""
    NEWVERSION=""

    if [[ "$EUID" -ne 0 ]]; then
        echo "Please run as root or sudo"
        exit 13 || return 13 # EACCES
    fi

    for arg in "$@"
    do
    case $arg in
        -y|-yes|--yes)
            YES=1
            shift # past the -y or --yes
        ;;

        http://*|https://*)
            ALTURL=$arg
            shift
        ;;

        *dtlinux-5.2.b.*.tgz)
           NEWVERSION=$arg
           TGZ=1
           CMDLINEFILE=1
           shift
        ;;

        *dtlinux-5.2.b.*.deb)
            if [ -f /etc/debian_version ]; then
                apt-cache show dtlinux >/dev/null 2>&1
                if [ 0 -eq $? ]; then
                    DEB=1
                    CMDLINEFILE=1
                    NEWVERSION=$arg
                    shift
                else
                    echo "DEB package not installed. Cannot update."
                    exit 2 || return 2 # ENOENT
                fi
            else
                echo "This is not a DEBian-based distro"
                exit 95 || return 95 # EOPNOTSUPP
           fi
        ;;

        *dtlinux-5.2.b.*.rpm)
            rpm -q dtlinux >/dev/null 2>&1

            if [ 0 -eq $? ]; then
                RPM=1
                NEWVERSION=$arg
                CMDLINEFILE=1
                shift
            else
                echo "RPM package not installed. Cannot update."
                exit 2 || return 2 # ENOENT
            fi
        ;;

        -h|-help|--help)
            echo "" # blank line
            echo "Syntax:"
            echo "  no arguments   check for updates"
            echo "  -y | --yes     answer yes to questions"
            echo "  -h | --help    display this page"
            echo "  dtlinux*tgz    update from named tgz"
            echo "  dtlinux*deb    update from named deb"
            echo "  dtlinux*rpm    update from named rpm"
            echo "" # blank line
            echo "You may specify an alternate server from"
            echo "which to fetch upgrades. The format is:"
            echo "" # blank line
            echo "  http://<server>[:port]/<path>/"
            echo "" # blank line
            echo "<server> may be an IP address or DNS name."
            echo "If :port is omitted, port 80 is used."
            echo "<path> must be the path where DTLinux"
            echo "update files are stored. If you are using"
            echo "Domain Time II Server on Windows as your"
            echo "source, then <path> must be \"dtlinux\""
            echo "" # blank line
            exit 0 || return 0
        ;;

        *)
            echo "Unknown argument: \"$arg\""
            echo "Use dtlinux-update --help"
            exit 95 || return 95 # EOPNOTSUPP
        ;;
 
    esac
    done

    if [[ "$NEWVERSION" != "" ]]; then 
        if [[ ! -f $NEWVERSION ]]; then
            echo "File $NEWVERSION not found"
            exit 2 || return 2 # ENOENT

        elif [ $YES -eq 0 ]; then
            echo "Do you want to install $NEWVERSION?"
            read -p "Press Y to continue: " -n 1 -r
            echo # blank line
        fi

    elif ! type wget &>/dev/null; then
        echo "This script requires wget"
        exit 2 || return 2 # ENOENT
    
    else
        #
        # Make sure dtcheck is present so we can compare version numbers
        #

        if [[ ! -f /opt/domtime/bin/dtcheck ]]; then
            echo "This script can only update, not install. DTLinux does"
            echo "not appear to be installed yet."
            exit 2 || return 2 # ENOENT
        fi

        #
        # Figure out if dtlinux was installed from a TGZ, RPM, or DEB
        #

        rpm -q dtlinux >/dev/null 2>&1

        if [ 0 -eq $? ]; then
            RPM=1

        elif [ -f /etc/debian_version ]; then
            apt-cache show dtlinux >/dev/null 2>&1
            if [ 0 -eq $? ]; then
                DEB=1
            fi
        fi

        if [ $DEB -eq 1 ]; then
            # A debian package is installed
            echo "Checking for a newer DEB"
            NEWVERSION=`/opt/domtime/bin/dtcheck -update -deb $ALTURL`

        elif [ $RPM -eq 1 ]; then
            # An RPM package is installed
            echo "Checking for a newer RPM"
            NEWVERSION=`/opt/domtime/bin/dtcheck -update -rpm $ALTURL`

        else
            # Neither RPM nor DEB detected
            echo "Checking for updates"
            NEWVERSION=`/opt/domtime/bin/dtcheck -update -tgz $ALTURL`
        fi

        if [[ -z $NEWVERSION ]]; then
            exit 0 || return 0 # Success
        fi

        #
        # prompt for confirmation
        #

        FILESOURCE=$(dirname $NEWVERSION)
        FILENAME=$(basename $NEWVERSION)

        echo "A new version is available from:"
        echo "    $FILESOURCE"
        echo "    $FILENAME"
        echo # blank line

        if [ $YES -eq 0 ]; then
            read -p "Do you want to install it? Press Y to continue: " -n 1 -r
            echo # blank line
        fi
    fi

    if [ $YES -eq 0 ]; then
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            echo "Update cancelled"
            exit 125 || return 125 # ECANCELED
        fi
    fi

    TMP_DIR=$(mktemp -d)

    if [ $CMDLINEFILE -eq 1 ]; then
        cp $NEWVERSION $TMP_DIR/
        pushd $TMP_DIR >/dev/null

    else
        pushd $TMP_DIR >/dev/null
        wget -nv $NEWVERSION
    fi

    if [ $DEB -eq 1 ]; then
       echo "Updating DEB"

       rm -f /opt/domtime/.tgz >/dev/null  # not installed by .tgz
       rm -f /opt/domtime/.rpm >/dev/null  # not installed by .rpm

       if [ ! -f /opt/domtime/.deb ]; then
          touch /opt/domtime/.deb # create zero-length file indicating installed by .deb
       fi

       echo N | apt-get install ./dtlinux*.deb >/dev/null 2>&1
       RET=$?
       if [ 0 -ne $RET ]; then
           echo "Something went wrong."
           echo "apt-get install failed with error code $RET"
       else
           echo "Update finished"
       fi
       popd >/dev/null

    elif [ $RPM -eq 1 ]; then
       echo "Updating RPM"

       rm -f /opt/domtime/.tgz >/dev/null # not installed by .tgz
       rm -f /opt/domtime/.deb >/dev/null # not installed by .deb

       if [ ! -f /opt/domtime/.rpm ]; then
          touch /opt/domtime/.rpm # create zero-length file indicating installed by .rpm
       fi

       rpm -U ./dtlinux*.rpm >/dev/null 2>&1
       RET=$?
       if [ 1 -eq $RET ]; then
           RET=0
           echo "DTLinux already up to date"
       fi

       if [ 0 -ne $RET ]; then
           echo "Something went wrong."
           echo "rpm -U failed with error code $RET"
       else
           echo "Update finished"
       fi
       popd >/dev/null
   
    else
       echo "Updating from TGZ"

       rm -f /opt/domtime/.deb >/dev/null # not installed by .deb
       rm -f /opt/domtime/.rpm >/dev/null # not installed by .rpm

       if [ ! -f /opt/domtime/.tgz ]; then
          touch /opt/domtime/.tgz # create zero-length file indicating installed by .tgz
       fi

       mkdir -p $TMP_DIR/unpacked
       tar -xf *.tgz -C unpacked

       popd  >/dev/null

       if [ -f $TMP_DIR/unpacked/install.sh ]; then
           $TMP_DIR/unpacked/install.sh
           RET=$?
             
           if [ 0 -ne $RET ]; then
               echo "Something went wrong."
               echo "install.sh failed with error code $RET"
           else
               echo "Update finished"
           fi
       else
           echo "Something went wrong"
           echo "Script install.sh not found"
           RET=2 # ENOENT
       fi
    fi

    if [ 0 -eq $RET ]; then

        if [ ! -e /usr/bin/dtcheck ]; then
            echo "    Making soft link to dtcheck in /usr/bin"
            ln -fs /opt/domtime/bin/dtcheck /usr/bin/dtcheck
        fi

        if [ ! -e /usr/bin/dtlinux ]; then
            echo "    Making soft link to dtlinux in /usr/bin"
            ln -fs /opt/domtime/bin/dtlinux /usr/bin/dtlinux
        fi

        if [ ! -e /usr/bin/dtlinux-update ]; then
            echo "    Making soft link /usr/bin/dtlinux-update"
            ln -fs /opt/domtime/update.sh /usr/bin/dtlinux-update
        fi
    fi

    rm -rf $TMP_DIR

    exit $RET || return $RET
}
