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

umask 077

: "${AGENTTEAM_ENV_FILE_PATH:?AGENTTEAM_ENV_FILE_PATH is required}"
: "${AGENTTEAM_ENV_CONTENT_B64:?AGENTTEAM_ENV_CONTENT_B64 is required}"

readonly SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/_lib.sh"

readonly ENV_FILE_PATH="$AGENTTEAM_ENV_FILE_PATH"
readonly ENV_CONTENT_B64="$AGENTTEAM_ENV_CONTENT_B64"
readonly REMOTE_ENV_PATH='/etc/agentteam/agentteam.env'

decode_base64() {
  if base64 -d </dev/null >/dev/null 2>&1; then
    base64 -d
    return 0
  fi
  if base64 -D </dev/null >/dev/null 2>&1; then
    base64 -D
    return 0
  fi
  echo "unsupported base64 implementation (needs -d or -D)" >&2
  return 1
}

if [[ -f "$ENV_FILE_PATH" ]]; then
  exit 0
fi

public_ip="${AGENTTEAM_PUBLIC_IP:?AGENTTEAM_PUBLIC_IP is required when local env file is missing}"
ssh_private_key_path="${AGENTTEAM_SSH_PRIVATE_KEY_PATH:?AGENTTEAM_SSH_PRIVATE_KEY_PATH is required when local env file is missing}"
ssh_port="${AGENTTEAM_SSH_PORT:-2222}"
ssh_user="${AGENTTEAM_SSH_USER:-ubuntu}"
known_hosts_path="${AGENTTEAM_SSH_KNOWN_HOSTS_PATH:?AGENTTEAM_SSH_KNOWN_HOSTS_PATH is required when local env file is missing}"

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"

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

cleanup() {
  rm -f "$tmp_path"
}
trap cleanup EXIT

if agentteam_ssh "$ssh_user@$public_ip" "sudo -n test -f '$REMOTE_ENV_PATH'"; then
  if ! agentteam_ssh "$ssh_user@$public_ip" "sudo -n cat '$REMOTE_ENV_PATH'" >"$tmp_path"; then
    echo "failed to pull remote env file: $REMOTE_ENV_PATH" >&2
    exit 1
  fi
  chmod 0600 "$tmp_path"
  mv -f "$tmp_path" "$ENV_FILE_PATH"

  echo "pulled remote env file into local: $ENV_FILE_PATH" >&2
  exit 0
fi

require_command base64

printf '%s' "$ENV_CONTENT_B64" | decode_base64 >"$tmp_path"
chmod 0600 "$tmp_path"
mv -f "$tmp_path" "$ENV_FILE_PATH"

echo "created local env file: $ENV_FILE_PATH" >&2
echo "hint: edit it (e.g. enable SES) then re-run scripts/release/sync-env.sh when ready." >&2
