#!/bin/sh

# DSM 5 -> 7 upgrade path:
# - Not supported
# DSM 6 -> 7 upgrade path:
# - files are migrated from ${SYNOPKG_PKGDEST}/var to ${SYNOPKG_PKGVAR}

# installer log is not writable, use for reference only.
INST_LOG="/var/log/packages/${SYNOPKG_PKGNAME}.log"

# Optional FWPORTS file
FWPORTS_FILE="/var/packages/${SYNOPKG_PKGNAME}/conf/${SYNOPKG_PKGNAME}.sc"

# Temporary directory when the package is upgrading
TMP_DIR="${SYNOPKG_TEMP_UPGRADE_FOLDER}"

install_log ()
{
    local _msg_="$@"
    if [ -z "${_msg_}" ]; then
        # read multiline from stdin
        while IFS=$'\n' read -r line; do
            install_log "${line}"
        done
    else
        # stderr goes to /var/log/packages/{package}.log
        # stdout goes to dialog in package manager ui.
        echo -e "$(date +'%Y/%m/%d %H:%M:%S')\t${_msg_}" 1>&2
    fi
}

# Invoke shell function if available
call_func ()
{
    FUNC=$1
    if type "${FUNC}" 2>/dev/null | grep -q 'function' 2>/dev/null; then
        install_log "Begin ${FUNC}"
        LOG=$2
        ARG=$3
        if [ -z "${LOG}" ]; then
            if [ -z "${ARG}" ]; then
                eval ${FUNC}
            else
                eval ${FUNC} ${ARG}
            fi
        else
            if [ -z "${ARG}" ]; then
                eval ${FUNC} 2>&1 | ${LOG}
            else
                eval ${FUNC} ${ARG} 2>&1 | ${LOG}
            fi
        fi
        install_log "End ${FUNC}"
    fi
}

# Source installer variables and functions
INST_FUNCTIONS=$(dirname $0)"/functions"
if [ -r "${INST_FUNCTIONS}" ]; then
    . "${INST_FUNCTIONS}"
fi


# Source package specific variables and functions
SVC_SETUP=$(dirname $0)"/service-setup"
if [ -r "${SVC_SETUP}" ]; then
    . "${SVC_SETUP}"
fi


# Load (wizard) variables stored by postinst
load_variables_from_file ${INST_VARIABLES}

# init variables either from ${INST_VARIABLES}, from package or from wizard
call_func "initialize_variables"


### Functions library

#
# syncronize all files from var folder in spk (extracted to target/var)
# (@appdata) /var/packages/<package>/target/var -> /var/packages/<package>/var
#
syno_sync_var_folder () {
    # take all files that do not alredy exist and rename the other files to *.new to avoid overwriting
    # existing configuration files.  Finally remove the target/var folder that is not used under DSM 7.
    _var=$(package_dir "${SYNOPKG_PKGDEST}/var") || return 0
    if [ -n "$(ls -A "${_var}" 2>/dev/null)" ] && [ -n "${SYNOPKG_PKGVAR}" ]; then

        echo "Install files from var folder"

        # Move all files except existing
        echo "$RSYNC --ignore-existing --remove-source-files ${_var}/ ${SYNOPKG_PKGVAR}"
        $RSYNC --ignore-existing --remove-source-files "${_var}/" "${SYNOPKG_PKGVAR}"

        # Rename any remaining (thus pre-existing) files with .new suffix
        find "${_var}" -type f -exec sh -c 'x="{}"; mv "$x" "${x}.new"' \;

        # Move .new files (overwrite existing)
        echo "$RSYNC --remove-source-files ${_var}/ ${SYNOPKG_PKGVAR}"
        $RSYNC --remove-source-files "${_var}/" "${SYNOPKG_PKGVAR}"

        # Remove var folder extraced from spk
        $RM "${_var}"
    fi
}

set_unix_permissions ()
{
    echo "Notice: set_unix_permissions() is no longer required on DSM7."
}

syno_remove_user ()
{
    echo "${SYNOPKG_PKGNAME} has not been updated to DSM7 yet. syno_remove_user() is no longer supported."
}

syno_group_create ()
{
    echo "${SYNOPKG_PKGNAME} has not been updated to DSM7 yet. syno_group_create() is no longer supported."
}

syno_group_remove ()
{
    echo "${SYNOPKG_PKGNAME} has not been updated to DSM7 yet. syno_group_remove() is no longer supported."
}

syno_user_add_to_group ()
{
    echo "${SYNOPKG_PKGNAME} has not been updated to DSM7 yet. syno_user_add_to_group() is no longer supported."
}

set_syno_permissions ()
{
    echo "${SYNOPKG_PKGNAME} has not been updated to DSM7 yet. set_syno_permissions() is no longer supported."
}

syno_user_add_to_legacy_group () {
    echo "${SYNOPKG_PKGNAME} has not been updated to DSM7 yet. syno_user_add_to_legacy_group() is no longer supported."
}


### Generic package behaviors

preinst ()
{
    log_step "preinst"
    call_func "validate_preinst"
    call_func "service_preinst" install_log

    exit 0
}

postinst ()
{
    log_step "postinst"
    call_func "save_wizard_variables" install_log

    # copy target/var data to permanent storage
    # and don't override old configurations
    call_func "syno_sync_var_folder" install_log

    call_func "service_postinst" install_log

    if [ -n "${LOG_FILE}" ]; then
        echo "Installation log: ${INST_LOG}" >> ${LOG_FILE}
    fi

    exit 0
}

preuninst ()
{
    log_step "preuninst"
    call_func "validate_preuninst"
    call_func "service_preuninst" install_log

    exit 0
}

postuninst ()
{
    log_step "postuninst"
    call_func "service_postuninst" install_log

    if [ "$wizard_delete_data" = "true" ]; then
        echo "Removing files..." | install_log
        for _path in "${SYNOPKG_PKGHOME}" "${SYNOPKG_PKGVAR}" "${INST_ETC}"; do
            if _dir=$(package_dir "${_path}"); then
                find "${_dir}" -mindepth 1 -delete 2>&1 | install_log
            else
                echo "Skip '${_path}': not an existing package directory" | install_log
            fi
        done
    fi

    exit 0
}

preupgrade ()
{
    log_step "preupgrade"
    call_func "validate_preupgrade"

    # dsm6 -> dsm7
    if _var=$(package_dir "${SYNOPKG_PKGDEST}/var"); then
        if [ ! -d "${SYNOPKG_PKGVAR}" ] || [ "$(realpath "${SYNOPKG_PKGVAR}")" = "${_var}" ]; then
            # Copy to temporary directory if upgrading from DSM6 -> DSM7
            # Then restore once to permanent storage at postupgrade
            if [ -n "${TMP_DIR}" ] && [ -n "$(ls -A "${_var}" 2>/dev/null)" ]; then
                echo "Backup target/var folder used under DSM6" | install_log
                echo "$RSYNC ${_var}/ ${TMP_DIR}" | install_log
                $RSYNC "${_var}/" "${TMP_DIR}" 2>&1 | install_log
                # remove DSM6 target/var folder
                rm -rf "${_var}" 2>&1 | install_log
            fi
        fi
    fi

    call_func "service_preupgrade" install_log
    call_func "service_save" install_log

    exit 0
}

postupgrade ()
{
    log_step "postupgrade"

    call_func "service_restore" install_log

    # dsm6 -> dsm7
    if [ -n "${TMP_DIR}" ] && [ -n "${SYNOPKG_PKGVAR}" ] && [ -n "$(ls -A "${TMP_DIR}" 2>/dev/null)" ]; then
        # Restore once to permanent storage at postupgrade
        echo "Resore var folder from DSM6" | install_log
        echo "$RSYNC ${TMP_DIR}/ ${SYNOPKG_PKGVAR}" | install_log
        $RSYNC "${TMP_DIR}/" "${SYNOPKG_PKGVAR}" 2>&1 | install_log
    fi

    # dsm7: Now sync in any new files to permanent storage
    call_func "syno_sync_var_folder" install_log
    call_func "service_postupgrade" install_log

    exit 0
}
