#!/usr/bin/env bash
set -euo pipefail
# LF-only: this script is executed directly from Linux/WSL.

ENV_DIR="/etc/ekamqr"
ENV_FILE="$ENV_DIR/ekamqr.env"
APP_ROOT="/opt/ekamqr"
SERVICE_NAME="ekamqr.service"
TTY="/dev/tty"

if [ "$(id -u)" -ne 0 ]; then
  echo "Run this command with sudo: sudo ekamqr-setup" >&2
  exit 1
fi

if [ ! -c "$TTY" ]; then
  echo "Interactive terminal is required. Run: sudo ekamqr-setup" >&2
  exit 1
fi

prompt_value() {
  label="$1"
  default_value="$2"
  if [ -n "$default_value" ]; then
    printf '%s [%s]: ' "$label" "$default_value" > "$TTY"
  else
    printf '%s: ' "$label" > "$TTY"
  fi
  IFS= read -r answer < "$TTY"
  if [ -z "$answer" ]; then
    answer="$default_value"
  fi
  printf '%s' "$answer"
}

prompt_secret() {
  label="$1"
  printf '%s: ' "$label" > "$TTY"
  stty -echo < "$TTY"
  IFS= read -r answer < "$TTY"
  stty echo < "$TTY"
  printf '\n' > "$TTY"
  printf '%s' "$answer"
}

env_escape() {
  printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}

random_base64() {
  openssl rand -base64 "$1" | tr -d '\n'
}

port_in_use() {
  ss -ltn 2>/dev/null | awk '{print $4}' | grep -Eq "[:.]$1$"
}

database_name_from_url() {
  value="$1"
  value="${value%%\?*}"
  printf '%s' "${value##*/}"
}

wait_for_postgres() {
  attempt=0
  while [ "$attempt" -lt 60 ]; do
    if runuser -u postgres -- pg_isready -p "$DB_PORT" >/dev/null 2>&1; then
      return 0
    fi
    attempt=$((attempt + 1))
    sleep 1
  done
  return 1
}

wait_for_app() {
  attempt=0
  while [ "$attempt" -lt 90 ]; do
    if curl -fsS --max-time 2 "http://127.0.0.1:$APP_PORT/api/health" >/dev/null 2>&1; then
      return 0
    fi
    if [ $((attempt % 10)) -eq 9 ]; then
      printf 'Waiting for EkamQR startup... %ss\n' "$((attempt + 1))" > "$TTY"
    fi
    attempt=$((attempt + 1))
    sleep 1
  done
  return 1
}

EXISTING=0
DEFAULT_COMPANY=""
DEFAULT_EMAIL=""
DEFAULT_ADMIN_EMAIL=""
DEFAULT_USERNAME="admin"
DEFAULT_PORT="8088"
DEFAULT_PUBLIC_URL=""
DEFAULT_DB_NAME="ekamqr"
DEFAULT_DB_USERNAME="ekamqr"
DB_PASSWORD=""
BIOMETRIC_KEY=""
NOTIFICATION_KEY=""

if [ -f "$ENV_FILE" ]; then
  EXISTING=1
  set -a
  . "$ENV_FILE"
  set +a
  DEFAULT_COMPANY="${PUNCHTIME_BOOTSTRAP_COMPANY_NAME:-}"
  DEFAULT_EMAIL="${PUNCHTIME_BOOTSTRAP_COMPANY_EMAIL:-}"
  DEFAULT_ADMIN_EMAIL="${PUNCHTIME_BOOTSTRAP_ADMIN_EMAIL:-}"
  DEFAULT_USERNAME="${PUNCHTIME_PRIMARY_ADMIN_USERNAME:-admin}"
  DEFAULT_PORT="${SERVER_PORT:-8088}"
  DEFAULT_PUBLIC_URL="${PUNCHTIME_PUBLIC_BASE_URL:-}"
  DEFAULT_DB_USERNAME="${PUNCHTIME_DB_USERNAME:-ekamqr}"
  if [ -n "${PUNCHTIME_DB_URL:-}" ]; then
    DEFAULT_DB_NAME="$(database_name_from_url "$PUNCHTIME_DB_URL")"
  fi
  DB_PASSWORD="${PUNCHTIME_DB_PASSWORD:-}"
  BIOMETRIC_KEY="$PUNCHTIME_BIOMETRIC_ENCRYPTION_KEY"
  NOTIFICATION_KEY="$PUNCHTIME_NOTIFICATION_ENCRYPTION_KEY"

  printf 'Existing EkamQR configuration found. Reconfigure it? [y/N]: ' > "$TTY"
  IFS= read -r confirm < "$TTY"
  case "$confirm" in
    y|Y|yes|YES) ;;
    *)
      echo "No changes made." > "$TTY"
      exit 0
      ;;
  esac

  systemctl stop "$SERVICE_NAME" >/dev/null 2>&1 || true
fi

echo > "$TTY"
echo "EkamQR Linux Server Setup" > "$TTY"
echo "-------------------------" > "$TTY"

while true; do
  COMPANY_NAME="$(prompt_value "Company name" "$DEFAULT_COMPANY")"
  [ -n "$COMPANY_NAME" ] && break
  echo "Company name is required." > "$TTY"
done

while true; do
  COMPANY_EMAIL="$(prompt_value "Company email" "$DEFAULT_EMAIL")"
  if printf '%s' "$COMPANY_EMAIL" | grep -Eq '^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$'; then
    break
  fi
  echo "Enter a valid company email address." > "$TTY"
done

if [ -z "$DEFAULT_ADMIN_EMAIL" ]; then
  DEFAULT_ADMIN_EMAIL="$COMPANY_EMAIL"
fi

while true; do
  ADMIN_EMAIL="$(prompt_value "Primary admin email" "$DEFAULT_ADMIN_EMAIL")"
  if printf '%s' "$ADMIN_EMAIL" | grep -Eq '^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$'; then
    ADMIN_EMAIL="$(printf '%s' "$ADMIN_EMAIL" | tr '[:upper:]' '[:lower:]')"
    break
  fi
  echo "Enter a valid primary admin email address." > "$TTY"
done

while true; do
  ADMIN_USERNAME="$(prompt_value "Primary admin username" "$DEFAULT_USERNAME")"
  if printf '%s' "$ADMIN_USERNAME" | grep -Eq '^[a-zA-Z0-9._-]{3,80}$'; then
    ADMIN_USERNAME="$(printf '%s' "$ADMIN_USERNAME" | tr '[:upper:]' '[:lower:]')"
    break
  fi
  echo "Username must contain 3-80 letters, numbers, dot, underscore or hyphen characters." > "$TTY"
done

ADMIN_PASSWORD=""
if [ "$EXISTING" -eq 0 ]; then
  while true; do
    ADMIN_PASSWORD="$(prompt_secret "Temporary admin password (minimum 12 characters)")"
    if [ "$(printf '%s' "$ADMIN_PASSWORD" | wc -c)" -lt 12 ]; then
      echo "Password must contain at least 12 characters." > "$TTY"
      continue
    fi
    ADMIN_PASSWORD_CONFIRM="$(prompt_secret "Confirm temporary admin password")"
    if [ "$ADMIN_PASSWORD" != "$ADMIN_PASSWORD_CONFIRM" ]; then
      echo "Passwords do not match." > "$TTY"
      continue
    fi
    break
  done
fi

while true; do
  APP_PORT="$(prompt_value "Application port" "$DEFAULT_PORT")"
  if ! printf '%s' "$APP_PORT" | grep -Eq '^[0-9]+$' || [ "$APP_PORT" -lt 1024 ] || [ "$APP_PORT" -gt 65535 ]; then
    echo "Choose a TCP port between 1024 and 65535." > "$TTY"
    continue
  fi
  if port_in_use "$APP_PORT"; then
    echo "Port $APP_PORT is already in use. Choose another port." > "$TTY"
    continue
  fi
  break
done

SERVER_IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
if [ -z "$DEFAULT_PUBLIC_URL" ]; then
  if [ -n "$SERVER_IP" ]; then
    DEFAULT_PUBLIC_URL="http://$SERVER_IP:$APP_PORT"
  else
    DEFAULT_PUBLIC_URL="http://localhost:$APP_PORT"
  fi
fi

while true; do
  PUBLIC_BASE_URL="$(prompt_value "Public application URL (used in password reset emails)" "$DEFAULT_PUBLIC_URL")"
  PUBLIC_BASE_URL="${PUBLIC_BASE_URL%/}"
  if printf '%s' "$PUBLIC_BASE_URL" | grep -Eq '^https?://[^[:space:]]+$'; then
    break
  fi
  echo "Enter a full http:// or https:// URL." > "$TTY"
done

while true; do
  DB_NAME="$(prompt_value "PostgreSQL database name" "$DEFAULT_DB_NAME")"
  if printf '%s' "$DB_NAME" | grep -Eq '^[a-z_][a-z0-9_]{0,62}$'; then
    break
  fi
  echo "Database name must start with a lowercase letter or underscore and contain only lowercase letters, numbers and underscores (max 63 characters)." > "$TTY"
done

while true; do
  DB_USERNAME="$(prompt_value "PostgreSQL database user" "$DEFAULT_DB_USERNAME")"
  if printf '%s' "$DB_USERNAME" | grep -Eq '^[a-z_][a-z0-9_]{0,62}$'; then
    break
  fi
  echo "Database user must start with a lowercase letter or underscore and contain only lowercase letters, numbers and underscores (max 63 characters)." > "$TTY"
done

SMTP_BOOTSTRAP_ENABLED="false"
SMTP_HOST=""
SMTP_PORT="587"
SMTP_USERNAME=""
SMTP_PASSWORD=""
SMTP_AUTH_ENABLED="true"
SMTP_STARTTLS_ENABLED="true"
SMTP_SSL_ENABLED="false"
SMTP_FROM_NAME="EkamQR"
SMTP_FROM_EMAIL="$COMPANY_EMAIL"

if [ "$EXISTING" -eq 0 ]; then
  printf 'Configure SMTP now for email password recovery? [Y/n]: ' > "$TTY"
  IFS= read -r configure_smtp < "$TTY"

  case "$configure_smtp" in
    n|N|no|NO)
      echo "SMTP skipped. Configure Email & SMS in EkamQR before relying on Forgot Password." > "$TTY"
      ;;
    *)
      while true; do
        SMTP_HOST="$(prompt_value "SMTP host" "")"
        [ -n "$SMTP_HOST" ] && break
        echo "SMTP host is required." > "$TTY"
      done

      while true; do
        SMTP_PORT="$(prompt_value "SMTP port" "587")"
        if printf '%s' "$SMTP_PORT" | grep -Eq '^[0-9]+$' && [ "$SMTP_PORT" -ge 1 ] && [ "$SMTP_PORT" -le 65535 ]; then
          break
        fi
        echo "Enter a valid SMTP port." > "$TTY"
      done

      SMTP_USERNAME="$(prompt_value "SMTP username (blank if not required)" "")"

      if [ -n "$SMTP_USERNAME" ]; then
        while true; do
          SMTP_PASSWORD="$(prompt_secret "SMTP password / app password")"
          [ -n "$SMTP_PASSWORD" ] && break
          echo "SMTP password is required when SMTP username is configured." > "$TTY"
        done
        SMTP_AUTH_ENABLED="true"
      else
        SMTP_AUTH_ENABLED="false"
      fi

      SMTP_FROM_EMAIL="$(prompt_value "From email" "$COMPANY_EMAIL")"

      printf 'Use STARTTLS? [Y/n]: ' > "$TTY"
      IFS= read -r starttls_answer < "$TTY"
      case "$starttls_answer" in
        n|N|no|NO) SMTP_STARTTLS_ENABLED="false" ;;
        *) SMTP_STARTTLS_ENABLED="true" ;;
      esac

      printf 'Use implicit SMTP SSL? [y/N]: ' > "$TTY"
      IFS= read -r ssl_answer < "$TTY"
      case "$ssl_answer" in
        y|Y|yes|YES) SMTP_SSL_ENABLED="true" ;;
        *) SMTP_SSL_ENABLED="false" ;;
      esac

      SMTP_BOOTSTRAP_ENABLED="true"
      ;;
  esac
fi

echo "Preparing PostgreSQL..." > "$TTY"
systemctl enable --now postgresql >/dev/null 2>&1

DB_PORT="$(pg_lsclusters --no-header 2>/dev/null | awk '$4 == "online" {print $3; exit}')"
if [ -z "$DB_PORT" ]; then
  DB_PORT="5432"
fi

if ! wait_for_postgres; then
  echo "PostgreSQL did not become ready on port $DB_PORT." > "$TTY"
  exit 1
fi

if [ -z "$DB_PASSWORD" ]; then
  DB_PASSWORD="$(random_base64 30)"
fi
if [ -z "$BIOMETRIC_KEY" ]; then
  BIOMETRIC_KEY="$(random_base64 32)"
fi
if [ -z "$NOTIFICATION_KEY" ]; then
  NOTIFICATION_KEY="$(random_base64 32)"
fi

ROLE_EXISTS="$(runuser -u postgres -- psql -p "$DB_PORT" -d postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='$DB_USERNAME'" | tr -d '[:space:]')"
DB_EXISTS="$(runuser -u postgres -- psql -p "$DB_PORT" -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" | tr -d '[:space:]')"

if [ "$EXISTING" -eq 0 ] && { [ "$ROLE_EXISTS" = "1" ] || [ "$DB_EXISTS" = "1" ]; }; then
  echo "Database '$DB_NAME' or role '$DB_USERNAME' already exists. Choose unique names for a fresh EkamQR installation." > "$TTY"
  exit 1
fi

if [ "$ROLE_EXISTS" != "1" ]; then
  runuser -u postgres -- psql -p "$DB_PORT" -v ON_ERROR_STOP=1 -d postgres     -v db_user="$DB_USERNAME" -v db_pass="$DB_PASSWORD" >/dev/null <<'SQL'
SELECT format('CREATE ROLE %I LOGIN PASSWORD %L', :'db_user', :'db_pass')
\gexec
SQL
else
  runuser -u postgres -- psql -p "$DB_PORT" -v ON_ERROR_STOP=1 -d postgres     -v db_user="$DB_USERNAME" -v db_pass="$DB_PASSWORD" >/dev/null <<'SQL'
SELECT format('ALTER ROLE %I WITH LOGIN PASSWORD %L', :'db_user', :'db_pass')
\gexec
SQL
fi

if [ "$DB_EXISTS" != "1" ]; then
  runuser -u postgres -- createdb -p "$DB_PORT" -O "$DB_USERNAME" "$DB_NAME"
else
  DB_OWNER="$(runuser -u postgres -- psql -p "$DB_PORT" -d postgres -tAc "SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname='$DB_NAME'" | tr -d '[:space:]')"
  if [ "$DB_OWNER" != "$DB_USERNAME" ]; then
    echo "Database '$DB_NAME' is owned by '$DB_OWNER', not '$DB_USERNAME'. Refusing to reuse it." > "$TTY"
    exit 1
  fi
fi

LICENSE_KEY_FILE="$APP_ROOT/config/license-public-key.b64"
if [ ! -f "$LICENSE_KEY_FILE" ]; then
  echo "License verification key is missing: $LICENSE_KEY_FILE" > "$TTY"
  exit 1
fi
LICENSE_KEY="$(tr -d '\r\n' < "$LICENSE_KEY_FILE")"

install -d -m 0750 -o root -g ekamqr "$ENV_DIR"
install -d -m 0750 -o ekamqr -g ekamqr /var/lib/ekamqr /var/lib/ekamqr/backups /var/log/ekamqr

BOOTSTRAP_ENABLED="false"
BOOTSTRAP_PASSWORD=""
if [ "$EXISTING" -eq 0 ]; then
  BOOTSTRAP_ENABLED="true"
  BOOTSTRAP_PASSWORD="$ADMIN_PASSWORD"
fi

APP_VERSION="$(cat "$APP_ROOT/VERSION" 2>/dev/null || printf 'development')"

cat > "$ENV_FILE" <<EOF
SPRING_PROFILES_ACTIVE="prod"
SERVER_PORT="$(env_escape "$APP_PORT")"
EKAMQR_APP_VERSION="$(env_escape "$APP_VERSION")"
SPRING_WEB_RESOURCES_STATIC_LOCATIONS="file:/opt/ekamqr/frontend/"
PUNCHTIME_DB_URL="jdbc:postgresql://127.0.0.1:$DB_PORT/$DB_NAME"
PUNCHTIME_DB_USERNAME="$(env_escape "$DB_USERNAME")"
EKAMQR_DB_NAME="$(env_escape "$DB_NAME")"
EKAMQR_DB_USERNAME="$(env_escape "$DB_USERNAME")"
PUNCHTIME_DB_PASSWORD="$(env_escape "$DB_PASSWORD")"
PUNCHTIME_DB_MAX_POOL_SIZE="12"
PUNCHTIME_POSTGRES_BIN="/usr/bin"
PUNCHTIME_FLYWAY_ENABLED="true"
PUNCHTIME_FLYWAY_BASELINE_ON_MIGRATE="true"
PUNCHTIME_JPA_DDL_AUTO="validate"
PUNCHTIME_BIOMETRIC_ENCRYPTION_KEY="$(env_escape "$BIOMETRIC_KEY")"
PUNCHTIME_NOTIFICATION_ENCRYPTION_KEY="$(env_escape "$NOTIFICATION_KEY")"
PUNCHTIME_LICENSE_PUBLIC_KEY="$(env_escape "$LICENSE_KEY")"
PUNCHTIME_CORS_ALLOWED_ORIGIN_PATTERNS="http://localhost:[*],https://localhost:[*],http://127.0.0.1:[*],https://127.0.0.1:[*],http://192.168.*:[*],https://192.168.*:[*],http://10.*:[*],https://10.*:[*],http://172.*:[*],https://172.*:[*],https://*.ts.net"
PUNCHTIME_SWAGGER_ENABLED="false"
PUNCHTIME_BOOTSTRAP_COMPANY_NAME="$(env_escape "$COMPANY_NAME")"
PUNCHTIME_BOOTSTRAP_COMPANY_EMAIL="$(env_escape "$COMPANY_EMAIL")"
PUNCHTIME_BOOTSTRAP_COMPANY_COUNTRY="India"
PUNCHTIME_BOOTSTRAP_COMPANY_TIMEZONE="Asia/Kolkata"
PUNCHTIME_BOOTSTRAP_COMPANY_CURRENCY="INR"
PUNCHTIME_BOOTSTRAP_ADMIN_ENABLED="$BOOTSTRAP_ENABLED"
PUNCHTIME_BOOTSTRAP_ADMIN_USERNAME="$(env_escape "$ADMIN_USERNAME")"
PUNCHTIME_BOOTSTRAP_ADMIN_PASSWORD="$(env_escape "$BOOTSTRAP_PASSWORD")"
PUNCHTIME_BOOTSTRAP_ADMIN_EMAIL="$(env_escape "$ADMIN_EMAIL")"
PUNCHTIME_PRIMARY_ADMIN_USERNAME="$(env_escape "$ADMIN_USERNAME")"
PUNCHTIME_LOCAL_ADMIN_RECOVERY_ENABLED="false"
PUNCHTIME_PUBLIC_BASE_URL="$(env_escape "$PUBLIC_BASE_URL")"
PUNCHTIME_PASSWORD_RESET_ENABLED="true"
PUNCHTIME_PASSWORD_RESET_TOKEN_VALIDITY_MINUTES="15"
EKAMQR_LINUX_UPDATE_ENABLED="true"
EKAMQR_UPDATE_MANIFEST_URL="https://ekamqr.com/downloads/linux/latest.json"
PUNCHTIME_BOOTSTRAP_SMTP_ENABLED="$SMTP_BOOTSTRAP_ENABLED"
PUNCHTIME_BOOTSTRAP_SMTP_HOST="$(env_escape "$SMTP_HOST")"
PUNCHTIME_BOOTSTRAP_SMTP_PORT="$(env_escape "$SMTP_PORT")"
PUNCHTIME_BOOTSTRAP_SMTP_USERNAME="$(env_escape "$SMTP_USERNAME")"
PUNCHTIME_BOOTSTRAP_SMTP_PASSWORD="$(env_escape "$SMTP_PASSWORD")"
PUNCHTIME_BOOTSTRAP_SMTP_AUTH_ENABLED="$SMTP_AUTH_ENABLED"
PUNCHTIME_BOOTSTRAP_SMTP_STARTTLS_ENABLED="$SMTP_STARTTLS_ENABLED"
PUNCHTIME_BOOTSTRAP_SMTP_SSL_ENABLED="$SMTP_SSL_ENABLED"
PUNCHTIME_BOOTSTRAP_SMTP_FROM_NAME="$(env_escape "$SMTP_FROM_NAME")"
PUNCHTIME_BOOTSTRAP_SMTP_FROM_EMAIL="$(env_escape "$SMTP_FROM_EMAIL")"
SPRING_WEB_RESOURCES_STATIC_LOCATIONS="file:/opt/ekamqr/frontend/"
EOF

chmod 0640 "$ENV_FILE"
chown root:ekamqr "$ENV_FILE"

systemctl daemon-reload
systemctl enable "$SERVICE_NAME" >/dev/null
systemctl restart "$SERVICE_NAME"

echo "Starting EkamQR and applying database migrations..." > "$TTY"
if ! wait_for_app; then
  echo "EkamQR did not become healthy within 90 seconds." > "$TTY"
  echo "Check: sudo journalctl -u ekamqr -n 200 --no-pager" > "$TTY"
  exit 1
fi

if [ "$BOOTSTRAP_ENABLED" = "true" ]; then
  sed -i 's/^PUNCHTIME_BOOTSTRAP_ADMIN_ENABLED=.*/PUNCHTIME_BOOTSTRAP_ADMIN_ENABLED="false"/' "$ENV_FILE"
  sed -i 's/^PUNCHTIME_BOOTSTRAP_ADMIN_PASSWORD=.*/PUNCHTIME_BOOTSTRAP_ADMIN_PASSWORD=""/' "$ENV_FILE"
fi

if [ "$SMTP_BOOTSTRAP_ENABLED" = "true" ]; then
  sed -i 's/^PUNCHTIME_BOOTSTRAP_SMTP_ENABLED=.*/PUNCHTIME_BOOTSTRAP_SMTP_ENABLED="false"/' "$ENV_FILE"
  sed -i 's/^PUNCHTIME_BOOTSTRAP_SMTP_PASSWORD=.*/PUNCHTIME_BOOTSTRAP_SMTP_PASSWORD=""/' "$ENV_FILE"
fi

if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q '^Status: active'; then
  ufw allow "$APP_PORT/tcp" >/dev/null 2>&1 || true
fi

echo > "$TTY"
echo "EkamQR installation completed successfully." > "$TTY"
echo "Service: running and enabled at startup" > "$TTY"
echo "PostgreSQL: running on local port $DB_PORT" > "$TTY"
echo "Application: http://localhost:$APP_PORT/" > "$TTY"
if [ -n "$SERVER_IP" ]; then
  echo "LAN URL: http://$SERVER_IP:$APP_PORT/" > "$TTY"
fi
echo "Admin username: $ADMIN_USERNAME" > "$TTY"
echo "Admin email: $ADMIN_EMAIL" > "$TTY"
echo "Database: $DB_NAME" > "$TTY"
echo "Database user: $DB_USERNAME" > "$TTY"
echo "Password reset URL base: $PUBLIC_BASE_URL" > "$TTY"
if [ "$SMTP_BOOTSTRAP_ENABLED" = "true" ]; then
  echo "Email password recovery: configured" > "$TTY"
else
  echo "Email password recovery: requires SMTP configuration in EkamQR" > "$TTY"
fi
if [ "$EXISTING" -eq 0 ]; then
  echo "Use the temporary password entered during setup; EkamQR will require a password change after login." > "$TTY"
fi
echo > "$TTY"
echo "Useful commands:" > "$TTY"
echo "  sudo systemctl status ekamqr" > "$TTY"
echo "  sudo journalctl -u ekamqr -f" > "$TTY"
