#!/bin/bash
# Run the complete release workflow: build, sign, promote, clean, sync

set -e

BUILD_ROOT=$(realpath "${BASH_SOURCE[0]%/*}/..")
source "$BUILD_ROOT/helpers/message-helpers.sh"
source "$BUILD_ROOT/helpers/paths.sh"

SYNC_REMOTE=""
SKIP_PROD_CHECK=false

print_header "Complete Release Workflow"

echo ""
print_info "This will run the complete release workflow:"
echo "  1. Build packages"
echo "  2. Sign packages"
echo "  3. Promote to production"
echo "  4. Clean old versions"
echo "  5. Sync to remote"
echo ""

# Parse arguments
BUILD_ARGS=()
while [[ $# -gt 0 ]]; do
  case $1 in
  --arch)
    ARCH="$2"
    BUILD_ARGS+=("--arch" "$2")
    shift 2
    ;;
  --package)
    BUILD_ARGS+=("--package" "$2")
    shift 2
    ;;
  --sync-remote)
    SYNC_REMOTE="$2"
    shift 2
    ;;
  --skip-prod-check)
    SKIP_PROD_CHECK=true
    shift
    ;;
  -h | --help)
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  --arch <arch>         Target architecture (x86_64 or aarch64, default: x86_64)"
    echo "  --package <name>      Build only the specified package"
    echo "  --sync-remote <path>  Rclone remote for sync (default: pkgs.omarchy.org:omarchy-pkgs)"
    echo "  --skip-prod-check     Skip production environment check during sync"
    echo "  -h, --help            Show this help message"
    echo ""
    echo "This script runs the complete workflow:"
    echo "  build → sign → promote → clean → sync"
    exit 0
    ;;
  *)
    print_error "Unknown option: $1"
    exit 1
    ;;
  esac
done

# Step 1: Build
echo ""
print_info "Step 1/5: Building packages..."
"$BUILD_ROOT/bin/build" "${BUILD_ARGS[@]}" || {
  print_error "Build failed"
  exit 1
}

# Step 2: Sign
echo ""
print_info "Step 2/5: Signing packages..."
"$BUILD_ROOT/bin/sign" --arch "$ARCH" || {
  print_error "Signing failed"
  exit 1
}

# Step 3: Promote
echo ""
print_info "Step 3/5: Promoting to production..."
"$BUILD_ROOT/bin/promote-build" --arch "$ARCH" || {
  print_error "Promotion failed"
  exit 1
}

# Step 4: Clean (which also updates the repo)
echo ""
print_info "Step 4/5: Cleaning old versions..."
"$BUILD_ROOT/bin/clean-repo" || {
  print_error "Cleaning failed"
  exit 1
}

# Step 5: Sync
echo ""
print_info "Step 5/5: Syncing to remote..."
SYNC_ARGS=("pkgs.omarchy.org/$ARCH")
if [[ -n "$SYNC_REMOTE" ]]; then
  SYNC_ARGS+=("--remote" "$SYNC_REMOTE")
fi
if [[ "$SKIP_PROD_CHECK" == true ]]; then
  SYNC_ARGS+=("--skip-prod-check")
fi
"$BUILD_ROOT/bin/sync-repo" "${SYNC_ARGS[@]}" || {
  print_error "Sync failed"
  exit 1
}

echo ""
print_success "Release workflow completed successfully!"
