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

usage() {
  cat <<USAGE
Usage:
  $0 <s3-key> <target-directory>

Example:
  $0 hfg01/hfdata-20260518.tar.gz /data/hfdata

What it does:
  1. Downloads a customer-file archive from s3://hangarforge-backups/<s3-key>
  2. Extracts it directly into <target-directory>

Requirements:
  - aws CLI configured with access to hangarforge-backups
  - tar available on the host
  - write access to the target directory
USAGE
}

[[ $# -eq 2 ]] || { usage; exit 1; }
command -v aws >/dev/null 2>&1 || { echo "aws CLI is required" >&2; exit 1; }
command -v tar >/dev/null 2>&1 || { echo "tar is required" >&2; exit 1; }

BUCKET="${HF_RECOVERY_S3_BUCKET:-hangarforge-backups}"
REGION="${AWS_REGION:-us-east-1}"
S3_KEY="$1"
TARGET_DIR="$2"

mkdir -p "$TARGET_DIR"
printf 'Restoring %s from s3://%s/%s into %s\n' "$S3_KEY" "$BUCKET" "$S3_KEY" "$TARGET_DIR"
aws s3 cp "s3://${BUCKET}/${S3_KEY}" - --region "$REGION" | tar -xzf - -C "$TARGET_DIR"

echo 'Customer file restore completed.'
