#!/bin/sh
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # #       EXECUTION ORDER       # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                   |                                      |                                    #
#   INSTALLATION                    |   UPGRADE                            |    UNINSTALLATION                  #
#                                   |                                      |                                    #
#      prereplace                   |      start-stop-status prestop       |      start-stop-status prestop     #
#  ->  preinst                      |      start-stop-status stop          |      start-stop-status stop        #
#      postinst                     |      preupgrade                      |      preuninst                     #
#      postreplace                  |      preuninst                       |      postuninst                    #
#      start-stop-status prestart   |      postuninst                      |                                    #
#      start-stop-status start      |      prereplace                      |                                    #
#                                   |  ->  preinst                         |                                    #
#                                   |      postinst                        |                                    #
#   START                           |      postreplace                     |                                    #
#                                   |      postupgrade                     |                                    #
#      start-stop-status prestart   |      start-stop-status prestart      |                                    #
#      start-stop-status start      |      start-stop-status start         |                                    #
#                                   |                                      |                                    #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

## Download RoonServer files on initial setup (not on upgrade)
if [ "${SYNOPKG_PKG_STATUS}" != "UPGRADE" ]; then

    # Others
    SSS="/var/packages/${SYNOPKG_PKGNAME}/scripts/start-stop-status"
    ROON_PKG_URL="https://download.roonlabs.net/builds/production1x/RoonServerLegacy_linuxx64.tar.bz2"
    ROON_ARCHIVE="${ROON_PKG_URL##*/}"
    R=0

    ## Check if RoonServer tar.bz is provided manually in database dir
    ## Get path from share_right.map as App Folder (../RoonServer/shares is not yet created.
    SHARE_CONF="/usr/syno/etc/share_right.map"
    
    ## function: if no path key is in the share section, check for guid section (relevant for esata/usb shares)
    check_esatashare_path() {
     ROON_DATABASE_SHARE_GUID=$(get_section_key_value "$SHARE_CONF" "$WIZARD_DATABASE_DIR" "guid") || exit
     ROON_DATABASE_SHARE_PATH=$(get_section_key_value "$SHARE_CONF" "$ROON_DATABASE_SHARE_GUID" "path") || exit
    }
    
    ## check path of selected database share. if it fails, run esatashare function
    ROON_DATABASE_SHARE_PATH=$(get_section_key_value "$SHARE_CONF" "$WIZARD_DATABASE_DIR" "path") || check_esatashare_path
    
    ROON_OFFLINE_ARCHIVE="${ROON_DATABASE_SHARE_PATH}/${ROON_ARCHIVE}"
    ## Create tmp directory
    tmp_dir=$(mktemp -d -t RoonServer-XXXXXXXXXX)

    pushd "${tmp_dir}" > /dev/null

    ## Getting binary file and extract it to unique tmp directory
    if $OFFLINEINSTALL ; then
        if [ -f ${ROON_OFFLINE_ARCHIVE} ]; then
            cp "${ROON_OFFLINE_ARCHIVE}" "${tmp_dir}"/ > /dev/null
            R=$?
                if [ $R -ne 0 ]; then
                    case $SYNOPKG_DSM_LANGUAGE in
                        enu)
                            ERRORMESSAGE="<br>Local installation archive in database directory could not been copied to the tmp directory."
                            ;;
                        ger)
                            ERRORMESSAGE="<br>Lokale Installationsdatei konnte nicht ins temporäre Verzeichnis (/tmp) kopiert werden."
                            ;;
                        *)
                            ERRORMESSAGE="<br>Local installation archive in database directory could not been copied to the tmp directory."
                            ;;
                        esac
                fi
        else
            R=1
            case $SYNOPKG_DSM_LANGUAGE in
                enu)
                    ERRORMESSAGE="Could not locate local installation archive.<br><br>File not found:<br>${ROON_OFFLINE_ARCHIVE}"
                    ;;
                ger)
                    ERRORMESSAGE="Es wurde keine lokale Installationsdatei gefunden.<br><br>Datei nicht gefunden:<br>${ROON_OFFLINE_ARCHIVE}"
                    ;;
                *)
                    ERRORMESSAGE="Could not locate local installation archive.<br><br>File not found:<br>${ROON_OFFLINE_ARCHIVE}"
                    ;;
            esac
        fi
    else
        ## Download RoonServer binary from roonlabs website
        STATUSCODE=$(curl --write-out '%{http_code}' -sLfO "$ROON_PKG_URL")
        R=$?
        if [ $R -ne 0 ]; then
            # Check domain, url, space on tmpdir and print error message
            TMPSPACE=`/bin/df -Ph /tmp | tail -1 | awk '{print $4}'`
            wait 5;
            case $SYNOPKG_DSM_LANGUAGE in
                enu)
                    ERRORMESSAGE="Could not download installation archive from Roon Labs website. Please check your internet connection.<br><b>URL:</b> $ROON_PKG_URL<br><b>HTTP status code:</b> $STATUSCODE<br><b>Available space in /tmp:</b> $TMPSPACE"
                    ;;
                ger)
                    ERRORMESSAGE="Download benötigter Dateien von der Roon Labs Webseite ist fehlgeschlagen. Bitte prüfe deine Internetverbindung.<br><b>URL:</b> $ROON_PKG_URL<br><b>HTTP Statuscode:</b> $STATUSCODE<br><b>Verfügbarer Speicher (/tmp):</b> $TMPSPACE"
                    ;;
                *)
                    ERRORMESSAGE="Could not download installation archive from Roon Labs website. Please check your internet connection.<br><b>URL:</b> $ROON_PKG_URL<br><b>HTTP status code:</b> $STATUSCODE<br><b>Available space in /tmp:</b> $TMPSPACE"
                    ;;
            esac
        fi
    fi

    ## Go on and extract the tar.bz2 file, if there has been no error
    if [ $R -eq 0 ]; then
        tar xjf "${ROON_ARCHIVE}" -C "${SYNOPKG_PKGINST_TEMP_DIR}"
        R=$?
        if [ $R -ne 0 ]; then
            case $SYNOPKG_DSM_LANGUAGE in
                enu)
                    ERRORMESSAGE="An error occured while extracting the installation archive. The archive might be corrupt or the tmp directory has no space left."
                    ;;
                ger)
                    ERRORMESSAGE="Es ist ein Fehler beim Entpacken des geladenen Roon Server Datei aufgetreten. Die Datei ist entweder beschädigt oder es ist nicht ausreichend freier Speicherplatz im tmp Verzeichnis verfügbar."
                    ;;
                *)
                    ERRORMESSAGE="An error occured while extracting the installation archive. The archive might be corrupt or the tmp directory has no space left."
                    ;;
            esac
        fi
    fi
    rm -R "${tmp_dir}"
    popd > /dev/null
fi

if [ $R -ne 0 ]; then
    echo "$ERRORMESSAGE" > $SYNOPKG_TEMP_LOGFILE
fi

exit $R
