#!/bin/sh

ws="server"
#ws="watch"

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

autostart_avail() {
    if [ "${ws}" = "watch" ]; then
        if desktop_enabled; then
            return 0
        else
            return 1
        fi
    fi
    if rc_avail || systemd_avail; then
        return 0
    else
        return 1
    fi
}

rc_avail() {
    if [ -d "/etc/appsinit.d" -o -d "/etc/extensions.d" ]; then
        return 0
    fi
    if [ -d "/etc/init.d" ]; then
        if [ -d "/etc/rc.d/extensions.d" ]; then
            return 0
        fi
        hash update-rc.d 2>/dev/null
        if [ $? -eq 0 -o -x /sbin/update-rc.d -o -x /usr/sbin/update-rc.d -o -x /usr/local/sbin/update-rc.d ]; then
            return 0
        fi
    fi
    return 1
}

systemd_avail() {
    if [ -d "/usr/lib/systemd/system" ]; then
        hash systemctl 2>/dev/null
        if [ $? -eq 0 -o -x /sbin/systemctl -o -x /usr/sbin/systemctl -o -x /usr/local/sbin/systemctl ]; then
            return 0
        fi
    fi
    return 1
}

autostart_enabled() {
    if [ "${ws}" = "watch" ]; then
        if desktop_enabled && [ -x "${HOME}/.config/autostart/minim${ws}.desktop" ]; then
            return 0
        else
            return 1
        fi
    else
        autostart_enabled_init
        return $?
    fi
}

autostart_enabled_init() {
    if rc_avail; then
        if [ -d "/etc/appsinit.d" ]; then
            INITDIR="/etc/appsinit.d"
        elif [ -d "/etc/extensions.d" ]; then
            INITDIR="/etc/extensions.d"
        else
            INITDIR="/etc/init.d"
        fi
    elif systemd_avail; then
        INITDIR="/usr/lib/systemd/system"
    else
        return 1
    fi
    if [ "${INITDIR}" != "/usr/lib/systemd/system" ]; then
        INITFILE="${INITDIR}/minim${ws}"
        if [ ! -x "${INITFILE}" ]; then
            return 1
        fi
        FOUND=$(grep "^ *${MINIMDIR}/bin/startd" ${INITFILE})
    else
        INITFILE="${INITDIR}/minim${ws}.service"
        if [ ! -f "${INITFILE}" ]; then
            return 1
        fi
        FOUND=$(grep "^ExecStart=${MINIMDIR}/bin/startd" ${INITFILE})
    fi
    if [ -z "${FOUND}" ]; then
        FOUND=$(grep "\-c \"${MINIMDIR}/bin/startd" ${INITFILE})
    fi
    if [ -n "${FOUND}" ]; then
        return 0
    else
        return 1
    fi
}

autostart_old() {
    if autostart_avail && rc_avail; then
        if [ -d "/etc/extensions.d" ]; then
            INITDIR="/etc/extensions.d"
        else
            INITDIR="/etc/init.d"
        fi
        INITFILE="${INITDIR}/minim${ws}"
        if [ ! -x "${INITFILE}" ]; then
            return 1
        fi
        grep "run init file as sourced script" ${INITFILE} >/dev/null 2>/dev/null
        if [ $? -eq 0 ]; then
            return 1
        else
            return 0
        fi
    else
        return 1
    fi
}

enable_autostart() {
    if autostart_avail; then
        if [ "${ws}" = "watch" ]; then
            autostart_file="${HOME}/.config/autostart/minim${ws}.desktop"
            if [ ! -x "$autostart_file" ]; then
                write_desktop_file "$autostart_file" "" "\"${MINIMDIR}/bin/starti\""
            fi
        else
            USERNAME="$1"
            if [ -z "${USERNAME}" ]; then
                if [ -n "${LOGNAME}" ]; then
                    USERNAME="${LOGNAME}"
                else
                    USERNAME="$(logname 2>/dev/null)"
                    if [ -z "${USERNAME}" ]; then
                        USERNAME="root"
                    fi
                fi
            fi
            if [ "$(id -u)" != "0" ]; then
                echo "Acquiring root privilege for system configuration update..."
                sudo "$0" enable_autostart "$USERNAME"
                return
            fi
            if rc_avail; then
                add_rc
            else
                add_systemd
            fi
        fi
    else
        echo "Minim${WS} automatic startup is not available" 1>&2
        exit 1
    fi
}

add_rc() {
    if [ -d "/etc/appsinit.d" ]; then
        INITDIR="/etc/appsinit.d"
        RCDIR="/etc/appsinit.d"
    elif [ -d "/etc/extensions.d" ]; then
        INITDIR="/etc/extensions.d"
        RCDIR="/etc/extensions.d"
    else
        INITDIR="/etc/init.d"
        if [ -d "/etc/rc.d/extensions.d" ]; then
            RCDIR="/etc/rc.d/extensions.d"
        else
            RCDIR=""
        fi
    fi
    INITFILE="${INITDIR}/minim${ws}"
    TEMPFILE="${INITFILE}.tmp"
    write_rc_start
    if [ -x "${INITFILE}" ]; then
        grep /bin/startd ${INITFILE} | grep -v "^ *${MINIMDIR}/bin/startd"  | grep -v "\-c \"${MINIMDIR}/bin/startd" >>${TEMPFILE}
    fi
    if [ "${USERNAME}" != "root" ]; then
        echo '        su "'${USERNAME}'" -c "'${MINIMDIR}'/bin/startd init" >>${INITLOGFILE} 2>&1' >>${TEMPFILE}
    else
        echo '        '${MINIMDIR}'/bin/startd init >>${INITLOGFILE} 2>&1' >>${TEMPFILE}
    fi
    write_rc_end
    chmod +x ${TEMPFILE} || exit
    if [ -x "${INITFILE}" ]; then
        mv ${TEMPFILE} ${INITFILE} || exit
    else
        mv ${TEMPFILE} ${INITFILE} || exit
        if [ "${RCDIR}" = "/etc/appsinit.d" -o "${RCDIR}" = "/etc/extensions.d" ]; then
            # needed for Melco N1
            ln -s ${INITFILE} ${RCDIR}/E50_minim${ws}.sh || exit
        elif [ "${RCDIR}" = "/etc/rc.d/extensions.d" ]; then
            # needed for Buffalo TeraStation
            ln -s ${INITFILE} ${RCDIR}/S40_minim${ws}.sh || exit
            ln -s ${INITFILE} ${RCDIR}/K60_minim${ws}.sh || exit
        else
            if [ -f "/etc/init.d/.legacy-bootordering" ]; then
                # needed for WD My Cloud
                update-rc.d minim${ws} start 99 2 3 4 5 . stop 01 0 1 6 . >/dev/null || exit
            else
                update-rc.d minim${ws} defaults >/dev/null || exit
            fi
        fi
    fi
}

add_systemd() {
    INITFILE="/usr/lib/systemd/system/minim${ws}.service"
    TEMPFILE="${INITFILE}.tmp"
    write_systemd_start
    if [ -f "${INITFILE}" ]; then
        grep /bin/startd ${INITFILE} | grep -v "^ExecStart=${MINIMDIR}/bin/startd" | grep -v "\-c \"${MINIMDIR}/bin/startd" >>${TEMPFILE}
    fi
    if [ "${USERNAME}" != "root" ]; then
        SU="$(which su)"
        echo "ExecStart=${SU} \"${USERNAME}\" -c \"${MINIMDIR}/bin/startd init\"" >>${TEMPFILE}
    else
        echo "ExecStart=${MINIMDIR}/bin/startd init" >>${TEMPFILE}
    fi
    echo "ExecStop=${MINIMDIR}/bin/stopall" >>${TEMPFILE}
    write_systemd_end
    if [ -f "${INITFILE}" ]; then
        mv ${TEMPFILE} ${INITFILE} || exit
        systemctl daemon-reload || exit
    else
        mv ${TEMPFILE} ${INITFILE} || exit
        systemctl daemon-reload || exit
        systemctl enable minim${ws}.service || exit
    fi
}

disable_autostart() {
    if autostart_avail; then
        if [ "${ws}" = "watch" ]; then
            rm -f ~/.config/autostart/minim${ws}.desktop
        else
            disable_autostart_init
        fi
    else
        echo "Minim${WS} automatic startup is not available" 1>&2
        exit 1
    fi
}

disable_autostart_init() {
    if [ "$(id -u)" != "0" ]; then
        echo "Acquiring root privilege for system configuration update..."
        sudo "$0" disable_autostart_init
        return
    fi
    if rc_avail; then
        remove_rc
    else
        remove_systemd
    fi
}

remove_rc() {
    if [ -d "/etc/appsinit.d" ]; then
        INITDIR="/etc/appsinit.d"
        RCDIR="/etc/appsinit.d"
    elif [ -d "/etc/extensions.d" ]; then
        INITDIR="/etc/extensions.d"
        RCDIR="/etc/extensions.d"
    else
        INITDIR="/etc/init.d"
        if [ -d "/etc/rc.d/extensions.d" ]; then
            RCDIR="/etc/rc.d/extensions.d"
        else
            RCDIR=""
        fi
    fi
    INITFILE="${INITDIR}/minim${ws}"
    [ ! -f "${INITFILE}" ] && return 0
    TEMPFILE="${INITFILE}.tmp"
    OTHERS=$(grep /bin/startd ${INITFILE} | grep -v "^ *${MINIMDIR}/bin/startd" | grep -v "\-c \"${MINIMDIR}/bin/startd")
    if [ -n "${OTHERS}" ]; then
        write_rc_start
        echo "${OTHERS}" >>${TEMPFILE}
        write_rc_end
        chmod +x ${TEMPFILE} || exit
        mv ${TEMPFILE} ${INITFILE} || exit
    else
        rm ${INITFILE} || exit
        if [ "${RCDIR}" = "/etc/appsinit.d" -o "${RCDIR}" = "/etc/extensions.d" ]; then
            rm -f ${RCDIR}/E50_minim${ws}.sh || exit
        elif [ "${RCDIR}" = "/etc/rc.d/extensions.d" ]; then
            rm -f ${RCDIR}/S40_minim${ws}.sh || exit
            rm -f ${RCDIR}/K60_minim${ws}.sh || exit
        else
            update-rc.d minim${ws} remove >/dev/null || exit
        fi
    fi
}

remove_systemd() {
    INITFILE="/usr/lib/systemd/system/minim${ws}.service"
    TEMPFILE="${INITFILE}.tmp"
    OTHERS=$(grep /bin/startd ${INITFILE} | grep -v "^ExecStart=${MINIMDIR}/bin/startd" | grep -v "\-c \"${MINIMDIR}/bin/startd")
    if [ -n "${OTHERS}" ]; then
        MINIMSTOPDIR=$(echo "${OTHERS}" | tail -n 1 | sed -n 's/ExecStart=\(.*\)\/startd.*/\1/p')
        if [ -z "${MINIMSTOPDIR}" ]; then
            MINIMSTOPDIR=$(echo "${OTHERS}" | tail -n 1 | sed -n 's/.*-c "\(.*\)\/startd.*/\1/p')
        fi
        if [ -z "${MINIMSTOPDIR}" ]; then
            echo "Minim${WS} stopall directory is not available" 1>&2
            exit 1
        fi
        write_systemd_start
        echo "${OTHERS}" >>${TEMPFILE}
        echo "ExecStop=${MINIMSTOPDIR}/bin/stopall" >>${TEMPFILE}
        write_systemd_end
        mv ${TEMPFILE} ${INITFILE} || exit
        systemctl daemon-reload || exit
    else
        systemctl disable minim${ws}.service || exit
        rm ${INITFILE} || exit
    fi
}

write_rc_start() {
    echo '#!/bin/sh' >${TEMPFILE} || exit
    echo '### BEGIN INIT INFO' >>${TEMPFILE}
    echo "# Provides: Minim${WS}" >>${TEMPFILE}
    echo '# Required-Start: $all' >>${TEMPFILE}
    echo '# Required-Stop: $all' >>${TEMPFILE}
    echo '# Default-Start: 2 3 4 5' >>${TEMPFILE}
    echo '# Default-Stop: 0 1 6' >>${TEMPFILE}
    echo "# Short-Description: Start and stop Minim${WS}" >>${TEMPFILE}
    echo '# Description:' >>${TEMPFILE}
    echo '### END INIT INFO' >>${TEMPFILE}
    echo '' >>${TEMPFILE}
    echo 'case "$1" in' >>${TEMPFILE}
    echo '    start)' >>${TEMPFILE}
    echo '        # run init file as sourced script' >>${TEMPFILE}
    echo "        [ -f \"${INITDIR}/minim${ws}-init.sh\" ] && . \"${INITDIR}/minim${ws}-init.sh\"" >>${TEMPFILE}
    echo '        [ -z "${INITLOGFILE}" ] && INITLOGFILE=/var/log/minim'${ws}'-init.log' >>${TEMPFILE}
    echo '        if [ -n "$INITLOGKEEP" ]; then' >>${TEMPFILE}
    echo '            ( touch "${INITLOGFILE}" 2>/dev/null ) || INITLOGFILE="/dev/null"' >>${TEMPFILE}
    echo '        else' >>${TEMPFILE}
    echo '            ( touch "${INITLOGFILE}" && rm "${INITLOGFILE}" 2>/dev/null ) || INITLOGFILE="/dev/null"' >>${TEMPFILE}
    echo '        fi' >>${TEMPFILE}
    #echo '        echo "Starting Minim'${WS}' at $(date)" >"${INITLOGFILE}" 2>/dev/null || INITLOGFILE="/dev/null"' >>${TEMPFILE}
}

write_rc_end() {
    echo '        ;;' >>${TEMPFILE}
    echo '    stop)' >>${TEMPFILE}
    echo '        PSOPT="-eo pid,user,vsz,stat,args"' >>${TEMPFILE}
    echo '        ps ${PSOPT} >/dev/null 2>&1 || PSOPT=""' >>${TEMPFILE}
    echo '        kill_time=0' >>${TEMPFILE}
    echo '        max_kill_time=5' >>${TEMPFILE}
    echo '        while :' >>${TEMPFILE}
    echo '        do' >>${TEMPFILE}
    echo '            PIDS="$(ps ${PSOPT} | grep m'"${ws}"'\.jar | grep -v grep | awk '"'"'{print $1}'"'"')"' >>${TEMPFILE}
    echo '            if [ -z "${PIDS}" ]; then' >>${TEMPFILE}
    echo '                break' >>${TEMPFILE}
    echo '            fi' >>${TEMPFILE}
    echo '            if [ ${kill_time} -eq 0 ]; then' >>${TEMPFILE}
    echo '                kill ${PIDS} 2>/dev/null' >>${TEMPFILE}
    echo '            elif [ ${kill_time} -eq ${max_kill_time} ]; then' >>${TEMPFILE}
    echo '                kill -9 ${PIDS} 2>/dev/null' >>${TEMPFILE}
    echo '                break' >>${TEMPFILE}
    echo '            fi' >>${TEMPFILE}
    echo '            kill_time=$((kill_time+1))' >>${TEMPFILE}
    echo '            sleep 1' >>${TEMPFILE}
    echo '        done' >>${TEMPFILE}
    echo '        ;;' >>${TEMPFILE}
    echo '    *)' >>/${TEMPFILE}
    echo '        echo "Usage: $0 start|stop" 1>&2' >>${TEMPFILE}
    echo '        exit 3' >>${TEMPFILE}
    echo '        ;;' >>${TEMPFILE}
    echo 'esac' >>${TEMPFILE}
}

write_systemd_start() {
    echo '[Unit]' >${TEMPFILE} || exit
    echo "Description=Minim${WS}" >>${TEMPFILE}
    echo 'After=multi-user.target' >>${TEMPFILE}
    echo '' >>${TEMPFILE}
    echo '[Service]' >>${TEMPFILE}
    echo 'Type=oneshot' >>${TEMPFILE}
    echo 'RemainAfterExit=yes' >>${TEMPFILE}
}

write_systemd_end() {
    echo '' >>${TEMPFILE}
    echo '[Install]' >>${TEMPFILE}
    echo 'WantedBy=multi-user.target' >>${TEMPFILE}
}

desktop_avail() {
    if [ -d "${DESKTOP_DIR}" ]; then
        return 0
    else
        return 1
    fi
}

desktop_enabled() {
    target_file="${DESKTOP_DIR}/minim${ws}.desktop"
    start_file="${DESKTOP_DIR}/minim${ws}.start"
    if [ -f "$target_file" ]; then
        exec_run=$(grep "Exec=.*minim${ws}/bin/starti" "$target_file")
        if [ -n "$exec_run" ]; then
            # single inline desktop entry
            exec_run_this=$(echo "$exec_run" | grep "${MINIMDIR}/bin/starti")
            if [ -n "$exec_run_this" ]; then
                # single desktop entry for this instance
                return 0
            else
                # single desktop entry for different instance
                return 1
            fi
        else
            if [ "${ws}" = "watch" ]; then
                echo "Incorrect format for desktop file" 1>&2
                exit 1
            fi
            exec_start=$(grep "Exec=.*minim${ws}.start" "$target_file")
            if [ -n "$exec_start" ]; then
                # desktop entry points to start file
                start_line=$(grep -n "${MINIMDIR}/bin/starti" $start_file)
                if [ -n "$start_line" ]; then
                    # contains start entry for this instance
                    return 0
                else
                    # no start entry for this instance
                    return 1
                fi
            else
                echo "Incorrect format for desktop file" 1>&2
                exit 1
            fi
        fi
    else
        # desktop file does not exist
        return 1
    fi
}

enable_desktop() {
    if [ ! -d "${DESKTOP_DIR}" ]; then
        echo "Minim${WS} desktop integration is not available" 1>&2
        exit 1
    fi
    if [ "${DESKTOP_DIR}" = "/usr/share/applications" ]; then
        enable_desktop_root
    else
        add_desktop_entry "${DESKTOP_DIR}" "${MINIMDIR}/icons/${ws}144.png" ""
    fi
    if [ "${ws}" = "server" ]; then
        add_desktop_entry "${HOME}/.config/autostart" "" " auto"
    fi
}

enable_desktop_root() {
   if [ "$(id -u)" != "0" ]; then
        echo "Acquiring root privilege for system configuration update..."
        sudo "$0" enable_desktop_root
        return
    fi
    add_desktop_entry "${DESKTOP_DIR}" "${MINIMDIR}/icons/${ws}144.png" ""
}

add_desktop_entry() {
    target_dir="$1"
    icon_file="$2"
    starti_arg="$3"
    target_file="$target_dir/minim${ws}.desktop"
    start_file="$target_dir/minim${ws}.start"

    if [ ! -d "$target_dir" ]; then
        mkdir -p "$target_dir" || exit
    fi

    if [ -f "$target_file" ]; then
        if [ "${ws}" = "watch" ]; then
            # desktop entry for MinimWatch already exists
            return 0
        fi
        exec_run=$(grep "Exec=.*minim${ws}/bin/starti" "$target_file")
        if [ -n "$exec_run" ]; then
            exec_run_this=$(echo "$exec_run" | grep "${MINIMDIR}/bin/starti")
            if [ -n "$exec_run_this" ]; then
                # desktop entry for MinimServer already exists
                return 0
            fi
            exec_run_cmd=$(echo "$exec_run" | cut -f2- -d'=')
            echo "$exec_run_cmd" >$start_file || exit
            echo "\"${MINIMDIR}/bin/starti\"$starti_arg" >>$start_file || exit
            exec_cmd="sh \"$start_file\""
        else
            exec_start=$(grep "Exec=.*minim${ws}.start" "$target_file")
            if [ -n "$exec_start" ]; then
                # update the start file
                start_line=$(grep "${MINIMDIR}/bin/starti" $start_file)
                if [ -n "$start_line" ]; then
                    # start file entry for MinimServer already exists
                    return 0
                fi
                echo "\"${MINIMDIR}/bin/starti\"$starti_arg" >>$start_file || exit
                exec_cmd="sh \"$start_file\""
            else
                echo "Incorrect format for desktop file" 1>&2
                exit 1
            fi
        fi
    else
        rm -f "$start_file"
        exec_cmd="\"${MINIMDIR}/bin/starti\"$starti_arg"
    fi

    write_desktop_file "$target_file" "$icon_file" "$exec_cmd" || exit
}

write_desktop_file() {
    target_file="$1"
    icon_file="$2"
    exec_cmd="$3"

    echo '[Desktop Entry]' > "$target_file"
    if [ $? -ne 0 ]; then
        echo "unable to write to file $target_file" 1>&2
        exit 1
    fi
    echo "Name=Minim${WS}" >> "$target_file" || exit
    if [ "${ws}" = "server" ]; then
        echo 'Comment=UPnP AV music server' >> "$target_file" || exit
    else
        echo 'Comment=Remote control for MinimServer' >> "$target_file" || exit
    fi
    echo "Exec=$exec_cmd" >> "$target_file" || exit
    # no quotes around the icon file path
    if [ -n "$icon_file" ]; then
        echo "Icon=$icon_file" >> "$target_file" || exit
    fi
    echo 'Terminal=false' >> "$target_file" || exit
    echo 'Type=Application' >> "$target_file" || exit
    echo 'Categories=Other;' >> "$target_file" || exit

    chmod +x "$target_file" || exit
}

disable_desktop() {
    if [ ! -d "${DESKTOP_DIR}" ]; then
        echo "Minim${WS} desktop integration is not available" 1>&2
        exit 1
    fi
    if [ "${DESKTOP_DIR}" = "/usr/share/applications" ]; then
        disable_desktop_root
    else
        remove_desktop_entry "${DESKTOP_DIR}"
    fi
    remove_desktop_entry "${HOME}/.config/autostart"
}

disable_desktop_root() {
   if [ "$(id -u)" != "0" ]; then
        echo "Acquiring root privilege for system configuration update..."
        sudo "$0" disable_desktop_root
        return
    fi
    remove_desktop_entry "${DESKTOP_DIR}"
}

remove_desktop_entry() {
    target_dir="$1"
    target_file="$target_dir/minim${ws}.desktop"
    start_file="$target_dir/minim${ws}.start"

    if [ -f "$target_file" ]; then
        exec_run=$(grep "Exec=.*minim${ws}/bin/starti" "$target_file")
        if [ -n "$exec_run" ]; then
            # single inline desktop entry
            exec_run_this=$(echo "$exec_run" | grep "${MINIMDIR}/bin/starti")
            if [ -n "$exec_run_this" ]; then
                # single desktop entry for this instance
                rm "$target_file" || exit
                return 0
            else
                # single desktop entry for different instance
                return 0
            fi
        else
            if [ "${ws}" = "watch" ]; then
                echo "Incorrect format for desktop file" 1>&2
                exit 1
            fi
            exec_start=$(grep "Exec=.*minim${ws}.start" "$target_file")
            if [ -n "$exec_start" ]; then
                # desktop entry points to start file
                start_line=$(grep -n "${MINIMDIR}/bin/starti" $start_file)
                if [ -n "$start_line" ]; then
                    # remove entry for this instance from start file
                    start_line_num=$(echo "$start_line" | cut -f1 -d':')
                    sed -i "${start_line_num}d" "$start_file"
                    start_lines=$(wc -l <"$start_file")
                    if [ "$start_lines" = "0" ]; then
                        rm "$start_file" "$target_file" || exit
                        return 0
                    else
                        if [ "$start_lines" = "1" ]; then
                            exec_cmd="$(cat "$start_file")"
                            start_cmd="$exec_cmd"
                        else
                            exec_cmd="sh \"$start_file\""
                            start_cmd=$(head -n 1 "$start_file")
                        fi
                        path_start_cmd="$(eval echo $start_cmd)"
                        path_bin="$(dirname $path_start_cmd)"
                        path_prefix="$(dirname $path_bin)"
                        icon_file="$path_prefix/icons/${ws}144.png"
                    fi
                else
                    # no start entry for this instance
                    return 0
                fi
            else
                echo "Incorrect format for desktop file" 1>&2
                exit 1
            fi
        fi
    else
        # desktop file does not exist
        return 0
    fi

    write_desktop_file "$target_file" "$path_prefix/icons/${ws}144.png" "$exec_cmd" || exit

    # ensure desktop file has been written successfully before doing this
    if [ "$start_lines" = "1" ]; then
        rm "$start_file" || exit
    fi
}

migrate() {
    # migrate saved configuration and/or other saved files
    MIGRATEDIR="$1"
    if [ -z "${MIGRATEDIR}" ]; then
        PARENTDIR="$(dirname "${MINIMDIR}")"
        MIGRATEDIR="${PARENTDIR}/.minim${ws}"
    else
        PARENTDIR="$(dirname "${MIGRATEDIR}")"
    fi
    if [ -d "${MIGRATEDIR}" ]; then
        if [ -x "${MIGRATEDIR}/bin/setup" ]; then
            # the previous setup script needs to be called from this location
            mv "${SCRIPTNAME}" "${SCRIPTDIR}/.setup" || exit
            OLDSETUP="${SCRIPTNAME}"
            mv "${MIGRATEDIR}/bin/setup" "${OLDSETUP}" || exit

            # check whether automatic startup and desktop integration are enabled
            if "${OLDSETUP}" autostart_enabled; then
                echo "Migrating Minim${WS} automatic startup to the new installation"
                migrate_autostart=true
                "${OLDSETUP}" disable_autostart
            fi
            if "${OLDSETUP}" desktop_enabled; then
                echo "Migrating Minim${WS} desktop integration to the new installation"
                migrate_desktop=true
                "${OLDSETUP}" disable_desktop
            fi

            # move files back to their correct places
            mv "${OLDSETUP}" "${MIGRATEDIR}/bin/setup" || exit
            mv "${SCRIPTDIR}/.setup" "${SCRIPTNAME}" || exit
        fi

        # migrate other configuration files
        ls "${MIGRATEDIR}"/data/* >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            mv "${MIGRATEDIR}"/data/* "${MINIMDIR}/data" || exit
            if [ -f "${MINIMDIR}/data/minim${ws}-out.log" ]; then
                rm -f "${MINIMDIR}/data/minim${ws}-out.log" 2>/dev/null
            fi
        fi
        ls "${MIGRATEDIR}"/libext/* >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            mv "${MIGRATEDIR}"/libext/* "${MINIMDIR}/libext" || exit
        fi
        ls "${MIGRATEDIR}"/libsys/* >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            mv "${MIGRATEDIR}"/libsys/* "${MINIMDIR}/libsys" || exit
        fi
        ls "${MIGRATEDIR}"/etc/* >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            mv "${MIGRATEDIR}"/etc/* "${MINIMDIR}/etc" || exit
        fi
        ls "${MIGRATEDIR}"/opt/* >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            mv "${MIGRATEDIR}"/opt/* "${MINIMDIR}/opt" || exit
        fi
        ls "${MIGRATEDIR}"/recent/* >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            if [ ! -d "${MINIMDIR}/recent" ]; then
                 mkdir "${MINIMDIR}/recent" || exit
            fi
            mv "${MIGRATEDIR}"/recent/* "${MINIMDIR}/recent" || exit
        fi
        if [ -d "${MIGRATEDIR}" ]; then
            rm -rf "${MIGRATEDIR}" || exit
        fi
        RC=0
    else
        RC=1
    fi

    # migrate previous desktop and autostart settings to the new installation
    if [ -n "$migrate_desktop" ]; then
        if desktop_avail; then
            enable_desktop
        else
            echo "Minim${WS} desktop integration is not available for the new installation"
        fi
    fi
    if [ -n "$migrate_autostart" ]; then
        if autostart_avail; then
            enable_autostart
        else
            echo "Minim${WS} automatic startup is not available for the new installation"
        fi
    fi

    return ${RC}
}

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}")"
MINIMDIR="$(dirname "${INSTALLDIR}")"
MINIMDIRBASE="$(basename "${MINIMDIR}")"
if [ "${MINIMDIRBASE}" != "minim${ws}" ]; then
    echo "Script location error: ${SCRIPTNAME}" 1>&2
    exit 1
fi
if [ -d "${HOME}/.local/share/applications" ]; then
    DESKTOP_DIR="${HOME}/.local/share/applications"
elif [ -d "/usr/share/applications" ]; then
    DESKTOP_DIR="/usr/share/applications"
elif [ -f "${HOME}/.config/user-dirs.dirs" ]; then
    XDG_DESKTOP_DIR="$(grep "^XDG_DESKTOP_DIR" "${HOME}/.config/user-dirs.dirs" | head -n 1 | cut -f2- -d'=')"
    eval DESKTOP_DIR=${XDG_DESKTOP_DIR}
else
    DESKTOP_DIR="${HOME}/Desktop"
fi


if [ "$1" = "autostart_avail" ]; then
    autostart_avail
    exit
elif [ "$1" = "autostart_enabled" ]; then
    autostart_enabled
    exit
elif [ "$1" = "enable_autostart" ]; then
    enable_autostart "$2"
    exit
elif [ "$1" = "disable_autostart" ]; then
    disable_autostart
    exit
elif [ "$1" = "disable_autostart_init" ]; then
    disable_autostart_init
    exit
elif [ "$1" = "desktop_avail" ]; then
    desktop_avail
    exit
elif [ "$1" = "desktop_enabled" ]; then
    desktop_enabled
    exit
elif [ "$1" = "enable_desktop" ]; then
    enable_desktop
    exit
elif [ "$1" = "enable_desktop_root" ]; then
    enable_desktop_root
    exit
elif [ "$1" = "disable_desktop" ]; then
    disable_desktop
    exit
elif [ "$1" = "disable_desktop_root" ]; then
    disable_desktop_root
    exit
elif [ "$1" = "migrate" ]; then
    migrate "$2"
    exit
fi

# perform migration actions if needed
migrate && echo "Saved configuration has been migrated"

echo ""
if desktop_avail; then
    if desktop_enabled; then
        echo "Minim${WS} desktop integration is enabled"
    else
        echo "Minim${WS} desktop integration is disabled"
    fi
else
    echo "Minim${WS} desktop integration is not available"
fi

if autostart_avail; then
    if autostart_enabled; then
        echo "Minim${WS} automatic startup is enabled"
    else
        echo "Minim${WS} automatic startup is disabled"
    fi
else
    echo "Minim${WS} automatic startup is not available"
fi

echo ""
if ! desktop_avail && ! autostart_avail; then
    exit
fi

while :
do
    echo "Do you want to change these settings (y/n)?"
    read LINE
    if [ "${LINE}" = "y" -o "${LINE}" = "Y" ]; then
        break
    elif [ "${LINE}" = "n" -o "${LINE}" = "N" ]; then
        exit 0
    fi
done

if desktop_avail; then
    while :
    do
        echo "Enable desktop integration for Minim${WS} (y/n)?"
        read LINE
        if [ "${LINE}" = "y" -o "${LINE}" = "Y" ]; then
            ENABLE=0
            break
        elif [ "${LINE}" = "n" -o "${LINE}" = "N" ]; then
            ENABLE=1
            break
        fi
    done
    NL=1
    if [ ${ENABLE} -eq 0 ]; then
        if ! desktop_enabled; then
            enable_desktop || exit
            echo "Minim${WS} desktop integration has been enabled"
            NL=0
        fi
    else
        if desktop_enabled; then
            disable_desktop || exit
            echo "Minim${WS} desktop integration has been disabled"
            if [ "${ws}" = "watch" ]; then
                echo "Minim${WS} automatic startup is not available"
            fi
            NL=0
        fi
    fi
    if [ ${NL} -eq 0 ]; then
        echo ""
    fi
fi

if autostart_avail; then
    while :
    do
        echo "Enable automatic startup for Minim${WS} (y/n)?"
        read LINE
        if [ "${LINE}" = "y" -o "${LINE}" = "Y" ]; then
            ENABLE=0
            break
        elif [ "${LINE}" = "n" -o "${LINE}" = "N" ]; then
            ENABLE=1
            break
        fi
    done
    NL=1
    if [ ${ENABLE} -eq 0 ]; then
        if ! autostart_enabled; then
            enable_autostart || exit
            echo "Minim${WS} automatic startup has been enabled"
            NL=0
        fi
    else
        if autostart_enabled; then
            disable_autostart || exit
            echo "Minim${WS} automatic startup has been disabled"
            NL=0
        fi
    fi
    if [ ${NL} -eq 0 ]; then
        echo ""
    fi
fi

exit 0
