#!/bin/bash

LOG_FILE="${TRIM_PKGVAR}/info.log"
PID_FILE="${TRIM_PKGVAR}/app.pid"
API_CGI="${TRIM_APPDEST}/www/api.cgi"
AUTO_MOUNT_STATE_FILE="${TRIM_PKGVAR}/auto-mounts.state"

# CGI runs on demand. Keep a lightweight status file so the app stays enabled.
CMD=""

log_msg() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >>${LOG_FILE}
}

list_auto_mounts() {
  [ -f "${AUTO_MOUNT_STATE_FILE}" ] || return 0
  awk -F'|' 'NF >= 3 && $1 != "" && $2 != "" { print $1 "|" $2 "|" $3 }' "${AUTO_MOUNT_STATE_FILE}" 2>/dev/null
}

run_cgi_action() {
  local request_payload="$1"
  local api_response=""
  local response_body=""

  [ -n "${request_payload}" ] || return 1
  [ -x "${API_CGI}" ] || return 1

  api_response=$(printf '%s' "${request_payload}" | CONTENT_LENGTH=${#request_payload} CONTENT_TYPE=application/x-www-form-urlencoded REQUEST_METHOD=POST bash "${API_CGI}" 2>/dev/null) || return 1
  response_body=$(printf '%s' "${api_response}" | sed -n '/^{/,$p')

  case "${response_body}" in
    *'"ok":true'*)
      return 0
      ;;
    *)
      if [ -n "${response_body}" ]; then
        log_msg "CGI action failed for ${request_payload}: ${response_body}"
      else
        log_msg "CGI action failed for ${request_payload}: empty response"
      fi
      return 1
      ;;
  esac
}

start_process() {
  if status; then
    return 0
  fi

  log_msg "Starting process ..."

  local active_boot_id=""
  active_boot_id=$(head -n 1 /proc/sys/kernel/random/boot_id 2>/dev/null | tr -d '[:space:]' || true)
  printf "%s" "${active_boot_id:-}" >"${PID_FILE}" 2>/dev/null

  run_cgi_action "action=activate"
  local device="" target="" mode=""
  while IFS='|' read -r device target mode; do
    [ -n "${device}" ] || continue
    [ -n "${target}" ] || continue
    [ -b "${device}" ] || {
      log_msg "Skip auto-mount, device missing: ${device}"
      continue
    }
    [ "${mode}" = "rw" ] || mode="ro"

    if run_cgi_action "action=mount&device=${device}&mode=${mode}&target=${target}"; then
      log_msg "Auto-mounted ${device} at ${target} (${mode})"
    else
      log_msg "Auto-mount failed for ${device} at ${target} (${mode})"
    fi
  done < <(list_auto_mounts)
  return 0
}

stop_process() {
  log_msg "Stopping process ..."

  run_cgi_action "action=shutdown"
  rm -f "${PID_FILE}"
  return 0
}

status() {
  if [ -f "${PID_FILE}" ]; then
    local record_boot_id="" active_boot_id=""
    record_boot_id=$(head -n 1 "${PID_FILE}" 2>/dev/null | tr -d '[:space:]' || true)
    active_boot_id=$(head -n 1 /proc/sys/kernel/random/boot_id 2>/dev/null | tr -d '[:space:]' || true)

    if [ -n "${record_boot_id}" ] && [ -n "${active_boot_id}" ] && [ "${record_boot_id}" = "${active_boot_id}" ]; then
      return 0
    fi

    rm -f "${PID_FILE}"
  fi

  return 1
}

case $1 in
  start)
    # run start command. exit 0 if success, exit 1 if failed
    start_process
    ;;
  stop)
    # run stop command. exit 0 if success, exit 1 if failed
    stop_process
    ;;
  status)
    # check application status command. exit 0 if running, exit 3 if not running
    if status; then
      exit 0
    else
      exit 3
    fi
    ;;
  *)
    exit 1
    ;;
esac
