#!/usr/bin/env bash

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

enforce_root

TRUE=1
FALSE=0

function die() {
    exit 1
}

get_web_service() {
    echo "apache2"
}

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 [ "`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

if [[ $DO_DB_SETUP -eq $TRUE ]]; then
    # load dbsetup
    /opt/dosis2/bin/os-support-service restart postgresql
    OLDPATH="`pwd`"
    cd /opt/dosis2/database
    ./db_setup.bash -s
    cd ${OLDPATH}
fi

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