### 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="gitea"
EFF_USER="sc-gitea"

# DSM name of shared folder from UI if provided
if [ -n "${wizard_shared_folder_name}" ]; then
   SHARE_PATH=$(realpath "/var/packages/${SYNOPKG_PKGNAME}/shares/${wizard_shared_folder_name}" 2> /dev/null)
   install_log "SHARE_PATH from share [${SHARE_PATH}], variable [wizard_shared_folder_name=${wizard_shared_folder_name}]"
   SHARE_NAME="${wizard_shared_folder_name}"
fi

# Service port
SERVICE_PORT="8418"

# 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
### ----------------------------------------

GITEA="${SYNOPKG_PKGDEST}/bin/gitea"
CONF_FILE="${SYNOPKG_PKGVAR}/conf.ini"
PATH="/var/packages/git/target/bin:${PATH}"

if [ $SYNOPKG_DSM_VERSION_MAJOR -lt 7 ]; then
    SYNOPKG_PKGHOME="${SYNOPKG_PKGVAR}"
fi

ENV="PATH=${PATH} HOME=${SYNOPKG_PKGHOME}"

SERVICE_COMMAND="env ${ENV} ${GITEA} web --port ${SERVICE_PORT} --pid ${PID_FILE}"
SVC_BACKGROUND=y

service_postinst ()
{
    if [ "${SYNOPKG_PKG_STATUS}" == "INSTALL" ]; then
        IP=$(ip route get 1 | awk '{print $(NF);exit}')

        sed -i -e "s|@share_path@|${SHARE_PATH}|g" ${CFG_FILE}
        sed -i -e "s|@ip_address@|${IP:=localhost}|g" ${CFG_FILE}
        sed -i -e "s|@service_port@|${SERVICE_PORT}|g" ${CFG_FILE}
    fi
}

# service_restore is called by post_upgrade before restoring files from ${TMP_DIR}
service_restore ()
{
    if [ ${SYNOPKG_DSM_VERSION_MAJOR} -lt 7 ]; then
        # make a copy of the new config file before it gets overwritten by restore
        # overwrite existing *.new files in ${TMP_DIR}/ as all files in ${TMP_DIR}/
        # are restored to ${SYNOPKG_PKGVAR}/
        [ -f "${SYNOPKG_PKGVAR}/conf.ini" ] && cp -f ${SYNOPKG_PKGVAR}/conf.ini ${TMP_DIR}/conf.ini.new
    fi
}