#!/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 KNOWN_HOSTS_PATH="$RELEASE_DIR/known_hosts"
readonly SCHEMA_BINARY_PATH="$RELEASE_DIR/agentteam-schema"
readonly REMOTE_SCHEMA_PATH='/tmp/agentteam-schema'
readonly REMOTE_ENV_PATH='/etc/agentteam/agentteam.env'

source "$SCRIPT_DIR/_lib.sh"

usage() {
  cat <<'EOF' >&2
Usage:
  scripts/release/migrate-db.sh [init|verify]

Environment variables:
  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)

This script builds the current `agentteam-schema` binary locally, uploads it to the
EC2 instance, sources `/etc/agentteam/agentteam.env`, and runs the requested schema
command remotely.
EOF
}

command_name="${1:-init}"
case "$command_name" in
  init|verify)
    ;;
  -h|--help|help)
    usage
    exit 0
    ;;
  *)
    usage
    echo "" >&2
    echo "unknown command: $command_name" >&2
    exit 1
    ;;
esac

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

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}"

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

require_command go
require_command scp
require_command ssh

mkdir -p "$RELEASE_DIR"

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"

(
  cd "$REPO_ROOT"
  GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -trimpath -o "$SCHEMA_BINARY_PATH" ./cmd/agentteam-schema
)

agentteam_scp "$SCHEMA_BINARY_PATH" "$ssh_user@$public_ip:$REMOTE_SCHEMA_PATH"
agentteam_ssh "$ssh_user@$public_ip" "chmod 0755 '$REMOTE_SCHEMA_PATH'"

cleanup_remote() {
  agentteam_ssh "$ssh_user@$public_ip" "rm -f '$REMOTE_SCHEMA_PATH'" >/dev/null 2>&1 || true
}
trap cleanup_remote EXIT

agentteam_ssh "$ssh_user@$public_ip" "sudo -n bash -lc 'set -euo pipefail; set -a; source \"$REMOTE_ENV_PATH\"; set +a; \"$REMOTE_SCHEMA_PATH\" \"$command_name\"'"

echo "agentteam schema command '$command_name' completed on $ssh_user@$public_ip:$ssh_port"
