#!/usr/bin/env bash
# Bootstrap Garage (S3) per replay Match Live TV — locale o produzione
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
GARAGE_CONTAINER="${GARAGE_CONTAINER:-infra-garage-1}"
BUCKET="${REPLAY_STORAGE_BUCKET:-matchlivetv-replays}"
KEY_NAME="${REPLAY_STORAGE_KEY_NAME:-replay-uploader}"
CREDS_FILE="${ROOT}/garage/dev-credentials.env"
ENV_FILE="${ROOT}/.env"

gexec() {
  docker exec "$GARAGE_CONTAINER" /garage "$@"
}

wait_garage() {
  echo "Attendo Garage..."
  for _ in $(seq 1 30); do
    if docker exec "$GARAGE_CONTAINER" /garage status >/dev/null 2>&1; then
      return 0
    fi
    sleep 1
  done
  echo "Garage non risponde. Avvia: cd $ROOT && docker compose up -d garage"
  exit 1
}

ensure_layout() {
  local node_id
  node_id="$(gexec status 2>/dev/null | awk '/^[0-9a-f]{16,}/{print $1; exit}')"
  if [ -z "$node_id" ]; then
    echo "Impossibile leggere node id da garage status"
    gexec status || true
    exit 1
  fi
  echo "Node id: $node_id"
  gexec layout assign -z dc1 -c 1G "$node_id" 2>/dev/null || true
  gexec layout apply --version 1 2>/dev/null || gexec layout apply 2>/dev/null || true
}

ensure_key() {
  if gexec key info "$KEY_NAME" >/dev/null 2>&1; then
    echo "Chiave $KEY_NAME già presente"
    return 0
  fi
  echo "Creazione chiave $KEY_NAME..."
  local out
  out="$(gexec key create "$KEY_NAME" 2>&1)"
  echo "$out"
  KEY_SECRET="$(echo "$out" | awk -F': ' '/Secret key/{print $2; exit}' | tr -d ' ')"
  if [ -z "$KEY_SECRET" ]; then
    KEY_SECRET="$(echo "$out" | grep -i secret | awk '{print $NF}' | head -1)"
  fi
  export KEY_SECRET
}

ensure_bucket() {
  echo "Bucket $BUCKET..."
  gexec bucket create "$BUCKET" 2>/dev/null || true
  gexec bucket allow \
    --read --write \
    --owner \
    "$BUCKET" \
    --key "$KEY_NAME" 2>/dev/null || \
  gexec bucket allow --read --write "$BUCKET" --key "$KEY_NAME" 2>/dev/null || true
}

write_credentials() {
  local key_id
  key_id="$(gexec key info "$KEY_NAME" 2>/dev/null | awk -F': ' '/Key ID|key id/{print $2; exit}' | tr -d ' ')"
  if [ -z "$key_id" ]; then
    key_id="$(gexec key info "$KEY_NAME" 2>/dev/null | grep -i 'key' | head -1 | awk '{print $NF}')"
  fi

  mkdir -p "${ROOT}/garage"
  cat > "$CREDS_FILE" <<EOF
# Generato da setup_garage_replays.sh — non committare
REPLAY_STORAGE_ENDPOINT=http://garage:3900
REPLAY_STORAGE_BUCKET=${BUCKET}
REPLAY_STORAGE_REGION=garage
REPLAY_STORAGE_ACCESS_KEY_ID=${key_id}
REPLAY_STORAGE_SECRET_ACCESS_KEY=${KEY_SECRET:-}
REPLAY_STORAGE_FORCE_PATH_STYLE=true
EOF

  echo ""
  echo "=== Credenziali Garage (replay) ==="
  gexec key info "$KEY_NAME" || true
  echo "File: $CREDS_FILE"
}

merge_into_env() {
  local key_id secret
  key_id="$(grep '^REPLAY_STORAGE_ACCESS_KEY_ID=' "$CREDS_FILE" | cut -d= -f2-)"
  secret="$(grep '^REPLAY_STORAGE_SECRET_ACCESS_KEY=' "$CREDS_FILE" | cut -d= -f2-)"
  if [ ! -f "$ENV_FILE" ]; then
    cp "${ROOT}/.env.example" "$ENV_FILE" 2>/dev/null || touch "$ENV_FILE"
  fi
  if grep -q '^REPLAY_STORAGE_ENDPOINT=' "$ENV_FILE" 2>/dev/null; then
    sed -i 's|^REPLAY_STORAGE_ENDPOINT=.*|REPLAY_STORAGE_ENDPOINT=http://garage:3900|' "$ENV_FILE"
    sed -i "s|^REPLAY_STORAGE_BUCKET=.*|REPLAY_STORAGE_BUCKET=${BUCKET}|" "$ENV_FILE"
    sed -i 's|^REPLAY_STORAGE_REGION=.*|REPLAY_STORAGE_REGION=garage|' "$ENV_FILE"
    sed -i "s|^REPLAY_STORAGE_ACCESS_KEY_ID=.*|REPLAY_STORAGE_ACCESS_KEY_ID=${key_id}|" "$ENV_FILE"
    sed -i 's|^REPLAY_STORAGE_FORCE_PATH_STYLE=.*|REPLAY_STORAGE_FORCE_PATH_STYLE=true|' "$ENV_FILE"
    if [ -n "$secret" ]; then
      if grep -q '^REPLAY_STORAGE_SECRET_ACCESS_KEY=' "$ENV_FILE" 2>/dev/null; then
        sed -i "s|^REPLAY_STORAGE_SECRET_ACCESS_KEY=.*|REPLAY_STORAGE_SECRET_ACCESS_KEY=${secret}|" "$ENV_FILE"
      else
        echo "REPLAY_STORAGE_SECRET_ACCESS_KEY=${secret}" >> "$ENV_FILE"
      fi
    fi
  else
    cat >> "$ENV_FILE" <<EOF

# Replay storage — Garage (generato da setup_garage_replays.sh)
REPLAY_STORAGE_ENDPOINT=http://garage:3900
REPLAY_STORAGE_BUCKET=${BUCKET}
REPLAY_STORAGE_REGION=garage
REPLAY_STORAGE_ACCESS_KEY_ID=${key_id}
REPLAY_STORAGE_SECRET_ACCESS_KEY=${secret}
REPLAY_STORAGE_FORCE_PATH_STYLE=true
EOF
  fi
  echo "Aggiornato $ENV_FILE (Garage replay storage)."
}

main() {
  cd "$ROOT"
  if ! docker ps --format '{{.Names}}' | grep -q "^${GARAGE_CONTAINER}$"; then
    echo "Avvio container garage..."
    docker compose up -d garage
  fi
  wait_garage
  ensure_layout
  ensure_key
  ensure_bucket
  write_credentials
  merge_into_env
  echo ""
  echo "Riavvia app: docker compose up -d rails sidekiq"
}

main "$@"
