#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

enforce_root

OS="`getos`"

TRUE=1
FALSE=0

function die() {
    exit 1
}

get_web_service() {
    if [ "${OS}" = "Ubuntu" ]; then
        echo "apache2"
    elif [ "${OS}" = "CentOS" ]; then
        echo "httpd"
    else
        abort 2 "Unsupported OS: ${OS}"
    fi
}

usage() {
    echo "Usage: update-from-prep [-h] [-b] [-s] [-d]"
    echo ""
    echo "-h                    show this usage message"
    echo "-b | --no-backup      do not do a database backup during update"
    echo "-s | --no-db-setup    do not run the database setup script during update (not common)"
    echo "-d | --dryrun         does a dry run update"
    echo ""
}

DO_BACKUP=$TRUE
DO_DB_SETUP=$TRUE
DO_DRY_RUN=$FALSE

while [ "$1" != "" ]; do
    case $1 in
        -b | --no-backup )      shift
                                DO_BACKUP=$FALSE
                                ;;
        -s | --no-db-setup )    DO_DB_SETUP=$FALSE
                                ;;
        -d | --dry-run )        DO_DRY_RUN=$TRUE
                                ;;
        -h | --help )           usage
                                exit
                                ;;
        * )                     usage
                                exit 1
    esac
    shift
done

/opt/dosis2/bin/os-support-service restart `get_web_service`

/opt/dosis2/bin/set-db-update-status TRUE

if [[ $DO_BACKUP -eq $TRUE ]]; then
    /usr/share/dosis2/bin/dosis-backup --rpm
fi

if [ "${OS}" = "Ubuntu" ]; then
    if [ "`ls /var/cache/apt/archives/*.deb`" != "" ]; then
        if [[ $DO_DRY_RUN -eq $TRUE ]]; then
            apt-get -s install /var/cache/apt/archives/*.deb || die
            /opt/dosis2/bin/set-db-update-status FALSE
            exit
        else
            DEBIAN_FRONTEND=noninteractive apt-get -yq -o DPkg::Options::="--force-confnew" install /var/cache/apt/archives/*.deb || die
        fi
    fi
elif [ "${OS}" = "CentOS" ]; then
    if [ "`ls /var/lib/dosis2/rpm/archives/*.rpm`" != "" ]; then
        if [[ $DO_DRY_RUN -eq $TRUE ]]; then
            rpm -Uvh --test /var/lib/dosis2/rpm/archives/*.rpm || die
            /opt/dosis2/bin/set-db-update-status FALSE
            exit
        else
            yum localinstall -y /var/lib/dosis2/rpm/archives/*.rpm || die
        fi
    fi
else
    echo "Unsupported OS: ${OS}"
fi

if [[ $DO_DB_SETUP -eq $TRUE ]]; then
    # load dbsetup
    if [ "${OS}" = "Ubuntu" ]; then
        /opt/dosis2/bin/os-support-service restart postgresql
        OLDPATH="`pwd`"
        cd /opt/dosis2/database
        ./db_setup.bash -s
        cd ${OLDPATH}
    elif [ "${OS}" = "CentOS" ]; then
        /opt/dosis2/bin/os-support-service restart postgresql-9.2
        pushd /opt/dosis2/database > /dev/null 2>&1
        ./db_setup.bash -s
        popd > /dev/null 2>&1
    else
        warning "Unknown OS: ${OS}"
    fi
fi

/opt/dosis2/bin/set-db-update-status FALSE