#!/bin/bash
# Post-installation script for WarpSend.
#
# DSM 7 runs third-party package lifecycle scripts as the package user.
# Keep postinst package-owned: prepare runtime dirs and seed config.toml.
# First-pair on Synology is gated by DSM weblogin (an administrator signs in
# on DSM's own page; the daemon verifies and mints a setup grant), so no
# secret is generated or stored here. DSM's web-config resource worker owns
# the HTTPS reverse proxy; legacy unmanaged nginx cleanup below is best-effort
# for developer/manual installs that run as root.

set -euo pipefail

PACKAGE_DIR="${WARPSEND_SPK_PACKAGE_DIR:-/var/packages/WarpSend/target}"
CONFIG_DIR="${WARPSEND_SPK_HOME_DIR:-/var/packages/WarpSend/home}"
PACKAGE_USER="${WARPSEND_SPK_USER:-WarpSend}"
PACKAGE_GROUP="${WARPSEND_SPK_GROUP:-WarpSend}"
NGINX_CONF="${WARPSEND_SPK_NGINX_CONF:-/usr/local/etc/nginx/conf.d/dsm.WarpSend.conf}"

maybe_chown() {
  if [ "$(id -u 2>/dev/null || echo 1)" = "0" ] && id "$PACKAGE_USER" >/dev/null 2>&1; then
    chown "$PACKAGE_USER:$PACKAGE_GROUP" "$@" 2>/dev/null || true
  fi
}

maybe_chown_recursive() {
  if [ "$(id -u 2>/dev/null || echo 1)" = "0" ] && id "$PACKAGE_USER" >/dev/null 2>&1; then
    chown -hR "$PACKAGE_USER:$PACKAGE_GROUP" "$@" 2>/dev/null || true
  fi
}

remove_legacy_nginx_proxy() {
  # Older SPKs installed this file directly as root. New packages register the
  # target/etc/nginx fragment through DSM's web-config resource worker instead.
  if [ -e "$NGINX_CONF" ]; then
    rm -f "$NGINX_CONF" 2>/dev/null || true
    if command -v nginx >/dev/null 2>&1; then
      nginx -s reload 2>/dev/null || true
    fi
  fi
}

extract_api_url() {
  awk -F'"' '/^[[:space:]]*api_url[[:space:]]*=/ {print $2; exit}' "$1" 2>/dev/null || true
}

is_known_baked_api_url() {
  case "$1" in
    https://api.warpsend.io|https://api-staging.warpsend.io) return 0 ;;
    *) return 1 ;;
  esac
}

rewrite_api_url_line() {
  local file="$1"
  local api_url="$2"
  local tmp="${file}.tmp.$$"

  awk -v api_url="$api_url" '
    /^[[:space:]]*api_url[[:space:]]*=/ && !rewritten {
      print "api_url = \"" api_url "\""
      rewritten = 1
      next
    }
    { print }
  ' "$file" > "$tmp"
  cat "$tmp" > "$file"
  rm -f "$tmp"
}

prepare_runtime_dirs() {
  # SlotManager writes managed binaries under $WARPSEND_CONFIG_DIR/bin at
  # runtime. Existing slot-a/slot-b contents are left intact here; on upgrade
  # the supervisor atomically stages the packaged agent + UI into the inactive
  # slot so its normal integrity checks and rollback behavior still apply.
  mkdir -p "${CONFIG_DIR}/.config/warpsend" "${CONFIG_DIR}/bin"
  chmod 700 "${CONFIG_DIR}" "${CONFIG_DIR}/.config" "${CONFIG_DIR}/.config/warpsend" 2>/dev/null || true
  chmod 700 "${CONFIG_DIR}/bin" 2>/dev/null || true
  maybe_chown "$CONFIG_DIR"
  maybe_chown_recursive "${CONFIG_DIR}/.config" "${CONFIG_DIR}/bin"
}

mark_package_bundle_refresh() {
  local marker="${CONFIG_DIR}/.config/warpsend/refresh-from-package"
  : > "$marker"
  chmod 600 "$marker" 2>/dev/null || true
  maybe_chown "$marker"
  echo "Marked packaged agent + UI bundle for one-shot supervisor activation."
}

seed_default_config() {
  # build-spk.sh bakes the env-specific api_url into package.tgz at
  # home/.config/warpsend/config.toml. DSM extracts that under target/, while
  # the runtime reads from /var/packages/WarpSend/home because start-stop-status
  # sets WARPSEND_CONFIG_DIR to the package home.
  local SEED="${PACKAGE_DIR}/home/.config/warpsend/config.toml"
  local DEST_DIR="${CONFIG_DIR}/.config/warpsend"
  local DEST="${DEST_DIR}/config.toml"

  if [ ! -f "$SEED" ]; then
    return 0
  fi

  if [ -f "$DEST" ]; then
    local seed_api_url current_api_url active_api_url
    seed_api_url="$(extract_api_url "$SEED")"
    current_api_url="$(extract_api_url "$DEST")"

    if [ -n "$seed_api_url" ] && is_known_baked_api_url "$current_api_url"; then
      if [ "$current_api_url" != "$seed_api_url" ]; then
        rewrite_api_url_line "$DEST" "$seed_api_url"
        chmod 600 "$DEST" 2>/dev/null || true
        maybe_chown "$DEST"
        echo "Updated $DEST api_url from baked default $current_api_url to $seed_api_url."
      else
        echo "Existing config.toml at $DEST already uses baked api_url $current_api_url."
      fi
    else
      echo "Existing config.toml at $DEST — leaving user customizations alone."
    fi

    active_api_url="$(extract_api_url "$DEST")"
    [ -z "$active_api_url" ] || echo "Active api_url: $active_api_url"
    return 0
  fi

  mkdir -p "$DEST_DIR"
  cp "$SEED" "$DEST"
  chmod 600 "$DEST" 2>/dev/null || true
  maybe_chown "$DEST"

  if [ ! -s "$DEST" ]; then
    echo "ERROR: seed_default_config: $DEST is missing or empty after cp!" >&2
    return 1
  fi
  if ! grep -q "^api_url" "$DEST"; then
    echo "ERROR: seed_default_config: $DEST has no api_url line!" >&2
    return 1
  fi
  echo "Seeded $DEST with api_url baked at SPK build time."
  echo "Active api_url: $(extract_api_url "$DEST")"
}

ACTION="${1:-${SYNOPKG_PKG_STATUS:-}}"
ACTION="$(printf '%s' "$ACTION" | tr '[:upper:]' '[:lower:]')"

case "$ACTION" in
  install)
    mkdir -p "$CONFIG_DIR"
    remove_legacy_nginx_proxy
    prepare_runtime_dirs
    seed_default_config
    ;;
  upgrade)
    mkdir -p "$CONFIG_DIR"
    remove_legacy_nginx_proxy
    prepare_runtime_dirs
    seed_default_config
    mark_package_bundle_refresh
    ;;
esac

exit 0
