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

readonly SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
readonly REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
readonly STACK_DIR="$REPO_ROOT/infra/aws-tokyo"
readonly RELEASE_DIR="$STACK_DIR/.terraform-build"
readonly DEFAULT_ENV_FILE_PATH="$STACK_DIR/agentteam.env.production"
readonly DEFAULT_KNOWN_HOSTS_PATH="$RELEASE_DIR/known_hosts"
readonly REMOTE_ENV_PATH='/etc/agentteam/agentteam.env'
readonly HEALTH_URL='http://127.0.0.1:3001/healthz'

source "$SCRIPT_DIR/_lib.sh"

trim_left() {
  local value="$1"
  value="${value#"${value%%[![:space:]]*}"}"
  printf '%s' "$value"
}

trim_right() {
  local value="$1"
  value="${value%"${value##*[![:space:]]}"}"
  printf '%s' "$value"
}

read_env_value() {
  local env_file_path="$1"
  local key="$2"

  local line=''
  while IFS= read -r line || [[ -n "$line" ]]; do
    line="${line%$'\r'}"
    line="$(trim_left "$line")"
    if [[ -z "$line" || "$line" == \#* ]]; then
      continue
    fi

    if [[ "$line" == export[[:space:]]* ]]; then
      line="${line#export}"
      line="$(trim_left "$line")"
    fi

    if [[ "$line" != "$key="* ]]; then
      continue
    fi

    local raw="${line#"$key="}"
    raw="$(trim_left "$raw")"
    if [[ -z "$raw" ]]; then
      return 0
    fi

    local first="${raw:0:1}"
    if [[ "$first" == "'" ]]; then
      raw="${raw:1}"
      if [[ "$raw" != *"'"* ]]; then
        echo "error: failed to parse $key (unterminated single quote) in env file: $env_file_path" >&2
        exit 1
      fi
      printf '%s' "${raw%%"'"*}"
      return 0
    fi
    if [[ "$first" == '"' ]]; then
      raw="${raw:1}"
      if [[ "$raw" != *'"'* ]]; then
        echo "error: failed to parse $key (unterminated double quote) in env file: $env_file_path" >&2
        exit 1
      fi
      printf '%s' "${raw%%\"*}"
      return 0
    fi

    raw="${raw%%#*}"
    raw="$(trim_right "$raw")"
    printf '%s' "$raw"
    return 0
  done

  return 1
}

usage() {
  cat <<'EOF' >&2
Usage:
  scripts/release/sync-env.sh

Environment variables:
  AGENTTEAM_ENV_FILE_PATH         (default: infra/aws-tokyo/agentteam.env.production)
  AGENTTEAM_PUBLIC_IP             (required unless Terraform state exists)
  AGENTTEAM_SSH_PRIVATE_KEY_PATH  (default: ~/.ssh/id_rsa)
  AGENTTEAM_SSH_PORT              (default: 2222)
  AGENTTEAM_SSH_USER              (default: ubuntu)
  AGENTTEAM_SSH_KNOWN_HOSTS_PATH  (default: infra/aws-tokyo/.terraform-build/known_hosts)
  AGENTTEAM_SYNC_ENV_RESTART      (default: 1; set to 0 to skip service restart)

This script uploads the local env file to the EC2 instance as:
  /etc/agentteam/agentteam.env

It does NOT run `terraform apply`.

Safety checks:
  - When AGENTTEAM_MAIL_DRIVER=ses, this script requires `aws` CLI and checks:
    - `sesv2:GetAccount.ProductionAccessEnabled` (must be true; not sandbox)
    - Sender identity is verified (either the exact from address identity, or its domain identity)
    If checks fail (or can't be determined), it refuses to sync to avoid breaking new-user registration.
EOF
}

public_ip="$(agentteam_resolve_public_ip "$STACK_DIR")"
if [[ -z "$public_ip" ]]; then
  usage
  echo "" >&2
  echo "AGENTTEAM_PUBLIC_IP is required (or run with Terraform + local state for infra/aws-tokyo)." >&2
  exit 1
fi

env_file_path="${AGENTTEAM_ENV_FILE_PATH:-$DEFAULT_ENV_FILE_PATH}"
ssh_private_key_path="${AGENTTEAM_SSH_PRIVATE_KEY_PATH:-$HOME/.ssh/id_rsa}"
ssh_port="${AGENTTEAM_SSH_PORT:-2222}"
ssh_user="${AGENTTEAM_SSH_USER:-ubuntu}"
known_hosts_path="${AGENTTEAM_SSH_KNOWN_HOSTS_PATH:-$DEFAULT_KNOWN_HOSTS_PATH}"
restart_service="${AGENTTEAM_SYNC_ENV_RESTART:-1}"

require_command ssh
require_command stat

if [[ ! -f "$env_file_path" ]]; then
  usage
  echo "" >&2
  echo "env file not found: $env_file_path" >&2
  echo 'hint: run `terraform apply` once (it will bootstrap infra/aws-tokyo/agentteam.env.production), or run `bash scripts/release/pull-env.sh` to pull from an existing instance.' >&2
  exit 1
fi

mail_driver="$(read_env_value "$env_file_path" 'AGENTTEAM_MAIL_DRIVER' || true)"
if [[ "$mail_driver" == "ses" ]]; then
  require_command aws

  ses_region="$(read_env_value "$env_file_path" 'AGENTTEAM_MAIL_SES_REGION' || true)"
  if [[ -z "$ses_region" ]]; then
    echo "error: AGENTTEAM_MAIL_SES_REGION is required when AGENTTEAM_MAIL_DRIVER=ses." >&2
    exit 1
  fi

  production_access_enabled_output=''
  if ! production_access_enabled_output="$(aws sesv2 get-account --region "$ses_region" --query 'ProductionAccessEnabled' --output text 2>&1)"; then
    echo "error: failed to query SES account state in region $ses_region (aws sesv2 get-account)." >&2
    echo "$production_access_enabled_output" >&2
    exit 1
  fi
  production_access_enabled="$(printf '%s' "$production_access_enabled_output" | tr -d '\r')"
  case "$production_access_enabled" in
    True|true)
      ;;
    False|false)
      echo "error: SES ProductionAccessEnabled=false (sandbox) in region $ses_region; refusing to sync env with AGENTTEAM_MAIL_DRIVER=ses." >&2
      echo "fix: request SES production access (leave sandbox), or set AGENTTEAM_MAIL_DRIVER=noop and re-run." >&2
      exit 1
      ;;
    *)
      echo "error: unexpected ProductionAccessEnabled output: $production_access_enabled (region $ses_region)." >&2
      exit 1
      ;;
  esac

  from_address="$(read_env_value "$env_file_path" 'AGENTTEAM_MAIL_FROM_ADDRESS' || true)"
  if [[ -z "$from_address" ]]; then
    echo "error: AGENTTEAM_MAIL_FROM_ADDRESS is required when AGENTTEAM_MAIL_DRIVER=ses." >&2
    exit 1
  fi
  if [[ "$from_address" != *"@"* || "$from_address" == *"<"* || "$from_address" == *">"* || "$from_address" =~ [[:space:]] ]]; then
    echo "error: AGENTTEAM_MAIL_FROM_ADDRESS must be a plain email address (e.g. noreply@example.com); got: $from_address" >&2
    exit 1
  fi

  identity_status=''
  identity_error=''
  if identity_status="$(aws sesv2 get-email-identity --region "$ses_region" --email-identity "$from_address" --query 'VerificationStatus' --output text 2>&1)"; then
    :
  else
    identity_error="$identity_status"
    identity_status=''
  fi

  from_domain=''
  if [[ "$from_address" == *"@"* ]]; then
    from_domain="${from_address#*@}"
  fi
  if [[ -z "$identity_status" && -n "$from_domain" ]]; then
    if identity_status="$(aws sesv2 get-email-identity --region "$ses_region" --email-identity "$from_domain" --query 'VerificationStatus' --output text 2>&1)"; then
      :
    else
      identity_error="$identity_status"
      identity_status=''
    fi
  fi

  identity_status="$(printf '%s' "$identity_status" | tr -d '\r')"
  if [[ "$identity_status" != "SUCCESS" ]]; then
    echo "error: SES sender identity is not verified for from address $from_address (region $ses_region)." >&2
    if [[ -n "$from_domain" ]]; then
      echo "fix: verify either the email identity ($from_address) or the domain identity ($from_domain) in SES, then re-run." >&2
    else
      echo "fix: verify the email identity ($from_address) in SES, then re-run." >&2
    fi
    if [[ -n "$identity_error" ]]; then
      echo "" >&2
      echo "aws sesv2 get-email-identity error:" >&2
      echo "$identity_error" >&2
    fi
    exit 1
  fi
fi

file_mode=''
if file_mode="$(stat -c '%a' "$env_file_path" 2>/dev/null)"; then
  :
elif file_mode="$(stat -f '%Lp' "$env_file_path" 2>/dev/null)"; then
  :
else
  echo "failed to detect file mode for env file: $env_file_path" >&2
  exit 1
fi

mode=$((8#$file_mode))
if (( (mode & 077) != 0 )); then
  echo "env file must not be readable by group/others: $env_file_path (mode $file_mode)" >&2
  echo "fix: chmod 0600 '$env_file_path'" >&2
  exit 1
fi

if [[ ! -f "$ssh_private_key_path" ]]; then
  echo "SSH private key not found: $ssh_private_key_path" >&2
  exit 1
fi

agentteam_prepare_known_hosts "$known_hosts_path"

agentteam_build_ssh_options "$ssh_private_key_path" "$ssh_port" "$known_hosts_path"
agentteam_wait_for_ssh "$ssh_user" "$public_ip" "$ssh_port"

remote_commands=(
  "sudo -n bash -c 'set -euo pipefail; umask 077; install -d -m 0755 /etc/agentteam; cat > /etc/agentteam/agentteam.env.tmp; mv -f /etc/agentteam/agentteam.env.tmp \"$REMOTE_ENV_PATH\"'"
)

if [[ "$restart_service" != "0" ]]; then
  remote_commands+=(
    "sudo -n systemctl restart agentteam-server"
    "sudo -n bash -c 'for attempt in {1..30}; do if curl -fsS --max-time 2 \"$HEALTH_URL\" >/dev/null; then exit 0; fi; sleep 2; done; echo \"agentteam server did not become healthy after env sync\" >&2; exit 1'"
  )
fi

agentteam_ssh "$ssh_user@$public_ip" "$(printf '%s && ' "${remote_commands[@]}") true" <"$env_file_path"

echo "synced env to $ssh_user@$public_ip:$ssh_port:$REMOTE_ENV_PATH"
