#!/bin/sh

ws="server"
WS="Server"
#ws="watch"
#WS="Watch"
SCRIPTNAME="$(readlink -f "$0")"
SCRIPTDIR="$(dirname "${SCRIPTNAME}")"
SCRIPTDIRBASE="$(basename "${SCRIPTDIR}")"
if [ "${SCRIPTDIRBASE}" != "bin" ]; then
    echo "Script location error: ${SCRIPTNAME}" 1>&2
    exit 1
fi
INSTALLDIR="$(dirname "${SCRIPTDIR}")"
INSTALLDIRBASE="$(basename "${INSTALLDIR}")"
MINIMDIR="$(dirname "${INSTALLDIR}")"
MINIMDIRBASE="$(basename "${MINIMDIR}")"
if [ "${MINIMDIRBASE}" != "minim${ws}" ]; then
    echo "Script location error: ${SCRIPTNAME}" 1>&2
    exit 1
fi
PARENTDIR="$(dirname "${MINIMDIR}")"

# check for migrate option (0.8.2 compatibility)
if  [ "$1" = "-m" ]; then
    "${SCRIPTDIR}/setup" migrate "$2"
    exit
fi

# locate the new archive
ARCHIVE_ARG=$1
while :
do
    if [ ! -z "${ARCHIVE_ARG}" ]; then
        ARCHIVE="${ARCHIVE_ARG}"
        ARCHIVE_ARG=""
    else
        echo "Enter name of new Minim${WS} archive:"
        read ARCHIVE
    fi
    if [ ! -f "${ARCHIVE}" ]; then
        echo "File not found: ${ARCHIVE}"
    else
        ARCHIVEBASE="$(basename "${ARCHIVE}")"
        case ${ARCHIVEBASE} in
            MinimWatch-*-linux-*.tar.gz)
                if [ "${ws}" = "watch" ]; then
                    break
                else
                    echo "Incorrect filename: ${ARCHIVEBASE}"
                fi
                ;;
            MinimServer-*-linux-*.tar.gz)
                if [ "${ws}" = "server" ]; then
                    break
                else
                    echo "Incorrect filename: ${ARCHIVEBASE}"
                fi
                ;;
            *)
                echo "Incorrect filename: ${ARCHIVEBASE}"
                ;;
        esac
    fi
done

# stop any running instances
"${SCRIPTDIR}/stopall" || exit

# backup the current installation
if [ -e "${PARENTDIR}/.minim${ws}" ]; then
    rm -rf "${PARENTDIR}/.minim${ws}" || exit
fi
mv "${PARENTDIR}/minim${ws}" "${PARENTDIR}/.minim${ws}" || exit

# unpack the new archive
tar -C "${PARENTDIR}" -xf "${ARCHIVE}" || exit

# migrate the current installation to the new installation
"${PARENTDIR}/minim${ws}/bin/setup" migrate "${PARENTDIR}/.minim${ws}" || exit

echo "Minim${WS} update completed successfully"

exit 0
