### Generic variables and functions
### -------------------------------

if [ -z "${SYNOPKG_PKGNAME}" ] || [ -z "${SYNOPKG_DSM_VERSION_MAJOR}" ]; then
  echo "Error: Environment variables are not set." 1>&2;
  echo "Please run me using synopkg instead. Example: \"synopkg start [packagename]\"" 1>&2;
  exit 1
fi

USER="nattunnel"
EFF_USER="sc-nattunnel"


# start-stop-status script redirect stdout/stderr to LOG_FILE
LOG_FILE="${SYNOPKG_PKGVAR}/${SYNOPKG_PKGNAME}.log"

# Service command has to deliver its pid into PID_FILE
PID_FILE="${SYNOPKG_PKGVAR}/${SYNOPKG_PKGNAME}.pid"


### Package specific variables and functions
### ----------------------------------------

PATH="${SYNOPKG_PKGDEST}/bin:${PATH}"
CFG_FILE="${SYNOPKG_PKGVAR}/settings.json"
LOG_DIR="${SYNOPKG_PKGVAR}/log"
NATTUNNEL="${SYNOPKG_PKGDEST}/bin/nattunnel"

SVC_BACKGROUND=y
SVC_WRITE_PID=y
SVC_CWD="${SYNOPKG_PKGDEST}/bin"

SERVICE_COMMAND="${NATTUNNEL}"

write_config ()
{
    # nattunnel.ini is shipped in bin/ by the package; only the log dir is created here
    mkdir -p "${LOG_DIR}"
    if [ -n "${EFF_USER}" ]; then
        chown -R "${EFF_USER}:${GROUP}" "${LOG_DIR}" 2>/dev/null || \
            chown -R "${EFF_USER}" "${LOG_DIR}" 2>/dev/null || \
            chown -R "${USER}" "${LOG_DIR}" 2>/dev/null
    fi
}

service_preinst ()
{
    # The token is mandatory on install (including CLI installs, which skip the wizard)
    case "${SYNOPKG_PKG_STATUS}" in
        UPGRADE|upgrade)
            ;;
        *)
            if [ -z "${token}" ]; then
                echo "The network token is required to install this package." >&2
                exit 1
            fi
            ;;
    esac
}

service_postinst ()
{
    write_config

    if [ -n "${token}" ]; then
        # Escape backslashes and double quotes before writing the token as JSON
        escaped_token=$(printf '%s' "${token}" | sed -e 's/[\\"]/\\&/g')
        printf '{\n    "token": "%s"\n}\n' "${escaped_token}" > "${CFG_FILE}"
    fi

    # DSM 6 only: remove the legacy user account created by old package versions
    if [ "${SYNOPKG_DSM_VERSION_MAJOR}" -lt 7 ]; then
        BIN="${SYNOPKG_PKGDEST}/bin"
        "${BIN}/busybox" --install "${BIN}"
        "${BIN}/delgroup" "${USER}" "users"
        "${BIN}/deluser" "${USER}"
    fi
}

service_prestart ()
{
    if [ -r "${CFG_FILE}" ]; then
        NETWORK_TOKEN=$(sed -n 's/.*"token"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "${CFG_FILE}")
    fi

    if [ -z "${NETWORK_TOKEN}" ]; then
        echo "No token found in ${CFG_FILE}, service not started." >> "${LOG_FILE}"
        SERVICE_COMMAND=""
        return
    fi

    SERVICE_COMMAND="${NATTUNNEL} -t${NETWORK_TOKEN}"
}

service_postupgrade ()
{
    # target/ is re-extracted on upgrade, so the ini and log dir must be recreated
    write_config

    # DSM 7 keeps the newly installed defaults next to existing files
    rm -f "${CFG_FILE}.new"
}
