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

umask 077

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'

source "$SCRIPT_DIR/_lib.sh"

usage() {
  cat <<'EOF' >&2
Usage:
  scripts/release/pull-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_PULL_ENV_OVERWRITE    (default: 0; set to 1 to overwrite local file)

This script downloads the server env file:
  /etc/agentteam/agentteam.env

into a local file:
  infra/aws-tokyo/agentteam.env.production
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}"
overwrite_local="${AGENTTEAM_PULL_ENV_OVERWRITE:-0}"

require_command ssh

if [[ -f "$env_file_path" && "$overwrite_local" != "1" ]]; then
  usage
  echo "" >&2
  echo "refusing to overwrite existing file: $env_file_path" >&2
  echo "set AGENTTEAM_PULL_ENV_OVERWRITE=1 to overwrite." >&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"

tmp_path="${env_file_path}.tmp.$$"
mkdir -p "$(dirname "$env_file_path")"

if ! agentteam_ssh "$ssh_user@$public_ip" "sudo -n cat '$REMOTE_ENV_PATH'" >"$tmp_path"; then
  rm -f "$tmp_path"
  echo "failed to read remote env file: $REMOTE_ENV_PATH" >&2
  exit 1
fi

chmod 0600 "$tmp_path"
mv -f "$tmp_path" "$env_file_path"

echo "pulled env to $env_file_path"
