#!/usr/bin/env bash
set -euo pipefail

# CMS Studio Linux One-Click Installer / Upgrader
# Usage:
#   curl -fsSL https://cms.aidonot.com/d/install.sh | sudo bash
#   CMS_DOMAIN=example.com CMS_EMAIL=admin@example.com bash install.sh
#   CMS_DIR=/opt/cms-studio CMS_PORT=80 CMS_AUTO_TLS=true bash install.sh
#   bash install.sh --uninstall

CMS_DIR="${CMS_DIR:-/opt/cms-studio}"
CMS_PORT="${CMS_PORT:-80}"
CMS_AUTO_TLS="${CMS_AUTO_TLS:-}"
CMS_DOMAIN="${CMS_DOMAIN:-}"
CMS_EMAIL="${CMS_EMAIL:-}"
CMS_PACKAGE_URL="${CMS_PACKAGE_URL:-https://cms.aidonot.com/d/cms-studio-latest-linux-amd64.tar.gz}"
SERVICE_NAME="cms-studio"

if [[ "${1:-}" == "--uninstall" ]]; then
  echo "==> Stopping and removing $SERVICE_NAME..."
  if command -v systemctl >/dev/null 2>&1; then
    systemctl stop "$SERVICE_NAME" 2>/dev/null || true
    systemctl disable "$SERVICE_NAME" 2>/dev/null || true
    rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
    systemctl daemon-reload 2>/dev/null || true
  fi
  echo "==> Service removed. Data directory preserved at: $CMS_DIR"
  exit 0
fi

need_cmd() {
  command -v "$1" >/dev/null 2>&1
}

download_file() {
  local url="$1"
  local dest="$2"
  if need_cmd curl; then
    curl -fL --progress-bar -o "$dest" "$url"
  elif need_cmd wget; then
    wget -O "$dest" "$url"
  else
    echo "Error: curl or wget is required." >&2
    exit 1
  fi
}

ARCH="$(uname -m)"
case "$ARCH" in
  x86_64|amd64) ;;
  *)
    echo "Error: unsupported architecture '$ARCH' (only linux/amd64 is packaged)." >&2
    exit 1
    ;;
esac

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT
PKG_PATH="$TMP_DIR/cms-studio-latest-linux-amd64.tar.gz"

echo "==> Downloading CMS Studio from $CMS_PACKAGE_URL..."
download_file "$CMS_PACKAGE_URL" "$PKG_PATH"

EXTRACT_DIR="$TMP_DIR/extract"
mkdir -p "$EXTRACT_DIR"
tar -xzf "$PKG_PATH" -C "$EXTRACT_DIR"

SRC_DIR="$EXTRACT_DIR"
BIN_SRC=""
for candidate in "cms-studio" "gocms"; do
  if [[ -f "$SRC_DIR/$candidate" ]]; then
    BIN_SRC="$SRC_DIR/$candidate"
    break
  fi
done
if [[ -z "$BIN_SRC" ]]; then
  FIRST_SUB="$(find "$EXTRACT_DIR" -mindepth 1 -maxdepth 1 -type d | head -n 1)"
  if [[ -n "$FIRST_SUB" ]]; then
    for candidate in "cms-studio" "gocms"; do
      if [[ -f "$FIRST_SUB/$candidate" ]]; then
        SRC_DIR="$FIRST_SUB"
        BIN_SRC="$FIRST_SUB/$candidate"
        break
      fi
    done
  fi
fi

if [[ -z "$BIN_SRC" ]]; then
  echo "Error: 'cms-studio' binary not found in archive." >&2
  exit 1
fi

echo "==> Installing to $CMS_DIR..."
mkdir -p "$CMS_DIR/data" "$CMS_DIR/themes" "$CMS_DIR/plugins"

if need_cmd systemctl && systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
  systemctl stop "$SERVICE_NAME"
fi

cp -f "$BIN_SRC" "$CMS_DIR/cms-studio"
chmod +x "$CMS_DIR/cms-studio"

if [[ -n "$CMS_DOMAIN" && -z "$CMS_AUTO_TLS" ]]; then
  CMS_AUTO_TLS="true"
fi

if [[ ! -f "$CMS_DIR/config.yaml" && -f "$SRC_DIR/config.yaml" ]]; then
  # Interactive TLS & domain/email prompt on fresh install when /dev/tty is available
  if [[ -z "$CMS_AUTO_TLS" ]]; then
    if [[ -r /dev/tty && -w /dev/tty ]]; then
      read -r -p "==> Enable automatic HTTPS (Let's Encrypt AutoTLS)? [Y/n]: " tls_ans < /dev/tty || true
      case "${tls_ans,,}" in
        n|no) CMS_AUTO_TLS="false" ;;
        *)    CMS_AUTO_TLS="true" ;;
      esac
    else
      CMS_AUTO_TLS="true"
    fi
  fi

  if [[ "$CMS_AUTO_TLS" == "true" && -r /dev/tty && -w /dev/tty ]]; then
    if [[ -z "$CMS_DOMAIN" ]]; then
      read -r -p "==> Enter domain(s) for TLS certificate (e.g. example.com, leave blank to configure later): " CMS_DOMAIN < /dev/tty || true
    fi
    if [[ -z "$CMS_EMAIL" ]]; then
      read -r -p "==> Enter email for Let's Encrypt expiry notices (optional): " CMS_EMAIL < /dev/tty || true
    fi
  fi

  cp "$SRC_DIR/config.yaml" "$CMS_DIR/config.yaml"
  if [[ "$CMS_PORT" != "8880" ]]; then
    sed -i -E "s|^([[:space:]]*port:[[:space:]]*).*|\1${CMS_PORT}|" "$CMS_DIR/config.yaml" || true
  fi
  NEW_JWT_SECRET=""
  if need_cmd openssl; then
    NEW_JWT_SECRET="$(openssl rand -hex 32 2>/dev/null || true)"
  elif [[ -r /dev/urandom ]]; then
    NEW_JWT_SECRET="$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' 2>/dev/null || true)"
  fi
  if [[ -n "$NEW_JWT_SECRET" ]]; then
    sed -i "s/gocms-super-secret-key-change-in-production-2026/${NEW_JWT_SECRET}/" "$CMS_DIR/config.yaml" || true
  fi
fi

# Apply explicit or interactive TLS settings to config.yaml (works for both fresh install and re-install)
if [[ -f "$CMS_DIR/config.yaml" ]]; then
  if [[ "$CMS_AUTO_TLS" == "true" ]]; then
    sed -i -E "s|^([[:space:]]*auto_tls:[[:space:]]*).*|\1true|" "$CMS_DIR/config.yaml" || true
  elif [[ "$CMS_AUTO_TLS" == "false" ]]; then
    sed -i -E "s|^([[:space:]]*auto_tls:[[:space:]]*).*|\1false|" "$CMS_DIR/config.yaml" || true
  fi
  if [[ -n "$CMS_DOMAIN" ]]; then
    ESCAPED_DOMAIN="$(printf '%s\n' "$CMS_DOMAIN" | sed 's/[\/&|]/\\&/g')"
    sed -i -E "s|^([[:space:]]*auto_tls_domain:[[:space:]]*).*|\1\"${ESCAPED_DOMAIN}\"|" "$CMS_DIR/config.yaml" || true
  fi
  if [[ -n "$CMS_EMAIL" ]]; then
    ESCAPED_EMAIL="$(printf '%s\n' "$CMS_EMAIL" | sed 's/[\/&|]/\\&/g')"
    sed -i -E "s|^([[:space:]]*auto_tls_email:[[:space:]]*).*|\1\"${ESCAPED_EMAIL}\"|" "$CMS_DIR/config.yaml" || true
  fi
fi
if [[ -z "$CMS_AUTO_TLS" ]]; then
  CMS_AUTO_TLS="true"
fi

if [[ -d "$SRC_DIR/themes/default" && ! -d "$CMS_DIR/themes/default" ]]; then
  cp -r "$SRC_DIR/themes/default" "$CMS_DIR/themes/"
fi

if [[ -d "$SRC_DIR/plugins" ]]; then
  for p in "$SRC_DIR/plugins"/*; do
    [[ -d "$p" ]] || continue
    pname="$(basename "$p")"
    if [[ ! -d "$CMS_DIR/plugins/$pname" ]]; then
      cp -r "$p" "$CMS_DIR/plugins/"
    fi
  done
fi

if [[ "$CMS_AUTO_TLS" == "true" ]]; then
  TLS_STATUS="Enabled (Let's Encrypt AutoTLS)"
  LISTEN_INFO=":443 (HTTPS) + :80 (HTTP -> HTTPS redirect)"
  if [[ -n "$CMS_DOMAIN" ]]; then
    PRIMARY_HOST="${CMS_DOMAIN%% *}"
    SITE_URL="https://${PRIMARY_HOST}"
  else
    SITE_URL="https://<your-domain>"
  fi
else
  TLS_STATUS="Disabled"
  LISTEN_INFO=":${CMS_PORT} (HTTP)"
  SITE_URL="http://127.0.0.1:${CMS_PORT}"
fi
ADMIN_URL="${SITE_URL}/admin/login"

print_install_summary() {
  local mode="$1"
  echo ""
  echo "===================================================================="
  echo " CMS Studio installed and started (${mode})!"
  echo "--------------------------------------------------------------------"
  echo " [Paths & Configuration]"
  echo "   Install Dir : $CMS_DIR"
  echo "   Config File : $CMS_DIR/config.yaml"
  echo "   Data Dir    : $CMS_DIR/data (SQLite DB & uploads)"
  echo "   Themes Dir  : $CMS_DIR/themes"
  echo "   Plugins Dir : $CMS_DIR/plugins"
  if [[ "$mode" == "systemd" ]]; then
    echo "   Unit File   : /etc/systemd/system/${SERVICE_NAME}.service"
  else
    echo "   Log File    : $CMS_DIR/cms-studio.log"
  fi
  echo "--------------------------------------------------------------------"
  echo " [Network & TLS]"
  echo "   TLS Mode    : $TLS_STATUS"
  echo "   Listen      : $LISTEN_INFO"
  echo "   Domain      : ${CMS_DOMAIN:-<not set - edit server.auto_tls_domain in config.yaml>}"
  echo "   TLS Email   : ${CMS_EMAIL:-<not set - edit server.auto_tls_email in config.yaml>}"
  if [[ "$CMS_AUTO_TLS" == "true" ]]; then
    echo "   Note        : Ensure your DNS A record points to this server and"
    echo "                 ports 80 & 443 are open in your firewall."
  fi
  echo "--------------------------------------------------------------------"
  echo " [Access & First-Run Setup]"
  echo "   Site URL    : $SITE_URL"
  echo "   Admin URL   : $ADMIN_URL"
  echo "   Setup Note  : No default password is set. Open Admin URL to create"
  echo "                 your initial administrator username and password."
  echo "--------------------------------------------------------------------"
  echo " [Management Commands]"
  if [[ "$mode" == "systemd" ]]; then
    echo "   Status      : systemctl status $SERVICE_NAME"
    echo "   Restart     : systemctl restart $SERVICE_NAME"
    echo "   Logs        : journalctl -u $SERVICE_NAME -f"
  else
    echo "   Logs        : tail -f $CMS_DIR/cms-studio.log"
  fi
  echo "   Uninstall   : bash install.sh --uninstall (keeps $CMS_DIR/data)"
  echo "===================================================================="
}

if need_cmd systemctl && [[ -d /etc/systemd/system ]]; then
  echo "==> Configuring systemd service ($SERVICE_NAME)..."
  cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
[Unit]
Description=CMS Studio Server
After=network.target

[Service]
Type=simple
WorkingDirectory=$CMS_DIR
ExecStart=$CMS_DIR/cms-studio
Restart=always
RestartSec=3
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  systemctl enable --now "$SERVICE_NAME"
  print_install_summary "systemd"
else
  echo "==> systemd not found, starting in background via nohup..."
  cd "$CMS_DIR"
  nohup "$CMS_DIR/cms-studio" > "$CMS_DIR/cms-studio.log" 2>&1 &
  echo "Started PID $!"
  print_install_summary "nohup"
fi
