#!/bin/sh

ws="server"
#ws="watch"

if [ "server" = "${ws}" ]; then
    WS="Server"
else
    WS="Watch"
fi

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}")"

# show prompt for saving the user configuration file
if [ -f "${MINIMDIR}/data/minim${ws}.config" ]; then
    if [ "$1" = "y" -o "$1" = "Y" ]; then
        SAVECONFIG=0
    elif [ "$1" = "n" -o "$1" = "N" ]; then
        SAVECONFIG=1
    else
        while :
        do
            echo "Do you want to save your Minim${WS} configuration file (y/n)?"
            read LINE
            if [ "${LINE}" = "y" -o "${LINE}" = "Y" ]; then
                SAVECONFIG=0
                break
            elif [ "${LINE}" = "n" -o "${LINE}" = "N" ]; then
                SAVECONFIG=1
                break
            fi
        done
    fi
else
    SAVECONFIG=1
fi

# remove links for automatic atartup
if "${SCRIPTDIR}/setup" autostart_enabled; then
    echo "Removing links for automatic startup..."
    "${SCRIPTDIR}/setup" disable_autostart || exit
fi

# remove desktop integration files
if "${SCRIPTDIR}/setup" desktop_enabled; then
    echo "Removing desktop integration files..."
    "${SCRIPTDIR}/setup" disable_desktop || exit
fi

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

# save configuration file if requested
if [ ${SAVECONFIG} -eq 0 ]; then
    echo "Saving Minim${WS} configuration file..."
    if [ -d "${PARENTDIR}/.minim${ws}" ]; then
        rm -rf "${PARENTDIR}/.minim${ws}" || exit
    fi
    mkdir -p "${PARENTDIR}/.minim${ws}/data" || exit
    cp -p "${MINIMDIR}/data/minim${ws}.config" "${PARENTDIR}/.minim${ws}/data" || exit
    ls "${MINIMDIR}"/data/*.profile >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        cp -p "${MINIMDIR}"/data/*.profile "${PARENTDIR}/.minim${ws}/data" || exit
    fi
    ls "${MINIMDIR}"/recent/* >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        mkdir "${PARENTDIR}/.minim${ws}/recent" || exit
        cp -p "${MINIMDIR}"/recent/* "${PARENTDIR}/.minim${ws}/recent" || exit
    fi
fi

echo "Removing Minim${WS} installation files..."
rm -rf ${MINIMDIR} || exit

echo "Minim${WS} has been uninstalled"

exit 0
