#!/bin/sh

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

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

INST_ETC="/var/packages/${SYNOPKG_PKGNAME}/etc"
INST_VARIABLES="${INST_ETC}/installer-variables"

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

TMP_DIR="${SYNOPKG_TEMP_UPGRADE_FOLDER}/var"


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
        if [ -z "${LOG}" ]; then
            eval ${FUNC}
        else
            eval ${FUNC} 2>&1 | ${LOG}
        fi
        install_log "End ${FUNC}"
    fi
}


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

# Reload wizard variables stored by postinst
if [ -r "${INST_VARIABLES}" ]; then
    . "${INST_VARIABLES}"
fi

# Expect user to be set from package specific variables
if [ -n "${USER}" -a -z "${USER_DESC}" ]; then
    USER_DESC="User running $SYNOPKG_PKGNAME"
fi

# Default description if group name provided by UI
if [ -n "${GROUP}" -a -z "${GROUP_DESC}" ]; then
    GROUP_DESC="SynoCommunity Package Group"
fi

# Extract share volume and share name from download location if provided
if [ -n "${SHARE_PATH}" ]; then
    SHARE_VOLUME=$(echo "${SHARE_PATH}" | awk -F/ '{print "/"$2}')
    SHARE_NAME=$(echo "${SHARE_PATH}" | awk -F/ '{print $3}')
fi

# Tools shortcuts
MV="/bin/mv -f"
RM="/bin/rm -rf"
CP="/bin/cp -rfp"
MKDIR="/bin/mkdir -p"
LN="/bin/ln -nsf"
TEE="/usr/bin/tee -a"

### Functions library

log_step ()
{
    install_log "===> Step $1. USER=$USER GROUP=$GROUP SHARE_PATH=${SHARE_PATH}"
}

save_wizard_variables ()
{
    if [ -e "${INST_VARIABLES}" ]; then
        $RM "${INST_VARIABLES}"
    fi
    if [ -n "${GROUP}" ]; then
        echo "GROUP=${GROUP}" >> ${INST_VARIABLES}
    fi
    if [ -n "${SHARE_PATH}" ]; then
        echo "SHARE_PATH=${SHARE_PATH}" >> ${INST_VARIABLES}
    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

    # Check volume exists
    if [ -n "${SHARE_PATH}" ]; then
        if [ ! -d "${SHARE_VOLUME}" ]; then
            echo "ERROR: Volume ${SHARE_VOLUME} does not exist." | $TEE 1>&2
            exit 1
        fi
    fi

    exit 0
}

postinst ()
{
    log_step "postinst"
    save_wizard_variables 2>&1 | install_log

    # copy target/var data to permanent storage
    # and don't override old configurations
    if [ -d ${SYNOPKG_PKGDEST}/var ] && [ "$(find ${SYNOPKG_PKGVAR} -mindepth 1 -not -name '*.log' -print)" = "" ]; then
        $CP ${SYNOPKG_PKGDEST}/var/. ${SYNOPKG_PKGVAR} 2>&1 | install_log
    fi    

    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

        if [ "$(ls -A ${SYNOPKG_PKGHOME})" != "" ]; then
            rm -rf ${SYNOPKG_PKGHOME}/* 2>&1 | install_log
        fi

        if [ "$(ls -A ${SYNOPKG_PKGVAR})" != "" ]; then
            rm -rf ${SYNOPKG_PKGVAR}/* 2>&1 | install_log
        fi

        if [ "$(ls -A /var/packages/${SYNOPKG_PKGNAME}/etc)" != "" ]; then
            rm -rf /var/packages/${SYNOPKG_PKGNAME}/etc/* 2>&1 | install_log
        fi
    fi
    exit 0
}

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

    # dsm6 -> dsm7
    # Migrate data to permanent storage
    if [ -d ${SYNOPKG_PKGDEST}/var -a ! "$(ls -A ${SYNOPKG_PKGVAR})" ]; then
        # only migrate when destination is empty
        $CP ${SYNOPKG_PKGDEST}/var/. ${SYNOPKG_PKGVAR} 2>&1 | install_log
    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
    call_func "service_postupgrade" install_log
    exit 0
}

