#!/bin/bash
#
# archive_trial_v2.sh
#
# Moves all "*trial-edition*" files under the current directory to S3,
# preserving the relative path structure.
#
# Usage:
#   ./archive_trial_v2.sh --dry-run     # preview only, no changes, no AWS calls needed
#   ./archive_trial_v2.sh --live        # actually perform the move (deletes local files on success)
#
# With no argument, defaults to --dry-run for safety.

# NOTE: AWS auth is handled via the AWS CLI profile (~/.aws/credentials),
# not via manually exported env vars. If you need a non-default profile,
# set AWS_PROFILE before running this script, e.g.:
#   export AWS_PROFILE=your-profile-name

MODE="${1:---dry-run}"

case "$MODE" in
    --dry-run)
        echo "=== DRY RUN MODE — no files will be uploaded or deleted ==="
        DRY_RUN=1
        ;;
    --live)
        echo "=== LIVE MODE — files will be uploaded to S3 and deleted locally on success ==="
        DRY_RUN=0
        ;;
    *)
        echo "Usage: $0 [--dry-run|--live]" >&2
        exit 1
        ;;
esac

find . -type f -name "*trial-edition*" -exec bash -c '
  dry_run="$1"
  shift
  ret=0
  count=0
  total_bytes=0
  for file do
    dest="s3://devops-team-bucket-dev/prod_nexus_version_archive/xld-trial-whole-sync/${file:2}"
    size=$(stat -c%s "$file" 2>/dev/null || stat -f%z "$file")
    total_bytes=$((total_bytes + size))
    count=$((count + 1))

    if [ "$dry_run" -eq 1 ]; then
      echo "[DRY RUN] Would move: $file  ->  $dest  ($(numfmt --to=iec --suffix=B "$size" 2>/dev/null || echo "${size} bytes"))"
    else
      echo "Moving: $file  ->  $dest"
      aws s3 mv "$file" "$dest" || ret="$?"
    fi
  done

  echo "----------------------------------------------------------"
  echo "Files matched: $count"
  echo "Total size: $(numfmt --to=iec --suffix=B "$total_bytes" 2>/dev/null || echo "${total_bytes} bytes")"
  exit "$ret"
' bash "$DRY_RUN" {} +
