#!/bin/bash
# =============================================================================
# LiveControl Bootstrap Installer
# =============================================================================
# Downloads and executes the full LiveControl installer from S3/CloudFront.
#
# Usage:
#   curl -fsSL https://get.cires21.com/livecontrol | bash
#   curl -fsSL https://get.cires21.com/livecontrol | bash -s -- --version 1.0.0
#
# =============================================================================

set -euo pipefail

# Configuration
# This URL will be replaced by the CI/CD pipeline or should be set to your CloudFront/S3 root
BASE_URL="https://get.cires21.com"
# Placeholder, overwritten by CI from the git tag at deploy time
BOOTSTRAP_VERSION="6.10.8"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; >&2; }

# Parse arguments and filter --keep-sources (bootstrap-only flag)
TARGET_VERSION="latest"
KEEP_SOURCES=0
FILTERED_ARGS=()

# Iterate through arguments:
# - Extract --version for download URL
# - Detect --keep-sources but don't pass it to install.sh
# - Pass all other arguments through
i=0
while [ $i -lt $# ]; do
    arg="${@:$((i+1)):1}"

    if [ "$arg" == "--version" ]; then
        # Extract version for download URL
        if [ $((i+1)) -lt $# ]; then
            TARGET_VERSION="${@:$((i+2)):1}"
            # Pass both --version and its value to install.sh
            FILTERED_ARGS+=("$arg")
            FILTERED_ARGS+=("$TARGET_VERSION")
            i=$((i+2))
            continue
        fi
    elif [ "$arg" == "--keep-sources" ]; then
        # Bootstrap-only flag: don't pass to install.sh
        KEEP_SOURCES=1
        i=$((i+1))
        continue
    fi

    # Pass all other arguments through
    FILTERED_ARGS+=("$arg")
    i=$((i+1))
done

# Prepare download URL
if [ "$TARGET_VERSION" == "latest" ]; then
    DOWNLOAD_URL="${BASE_URL}/assets/latest/livecontrol-deploy-latest.tar.gz"
else
    DOWNLOAD_URL="${BASE_URL}/assets/${TARGET_VERSION}/livecontrol-deploy-${TARGET_VERSION}.tar.gz"
fi

# Temporary directory
TMP_DIR=$(mktemp -d)

# Conditional cleanup trap - skip if --keep-sources is specified
if [ "$KEEP_SOURCES" -eq 0 ]; then
    trap 'rm -rf "$TMP_DIR"' EXIT
fi

log_info "LiveControl Bootstrap v${BOOTSTRAP_VERSION}"
log_info "Target version: ${TARGET_VERSION}"
log_info "Downloading installer..."

# Download TGZ
if ! curl -fsSL "$DOWNLOAD_URL" -o "$TMP_DIR/installer.tar.gz"; then
    log_error "Failed to download installer from: $DOWNLOAD_URL"
    log_error "Please check the version number and try again."
    exit 1
fi

# Verify integrity via SHA256 checksum
CHECKSUM_URL="${DOWNLOAD_URL}.sha256"
EXPECTED_HASH=$(curl -fsSL "$CHECKSUM_URL" 2>/dev/null | awk '{print $1}')
if [ -n "$EXPECTED_HASH" ]; then
    log_info "Verifying checksum..."
    ACTUAL_HASH=$(sha256sum "$TMP_DIR/installer.tar.gz" | awk '{print $1}')
    if [ "$EXPECTED_HASH" != "$ACTUAL_HASH" ]; then
        log_error "Checksum verification failed! The downloaded file may be corrupted."
        exit 1
    fi
    log_success "Checksum verified"
else
    log_info "No checksum file available, skipping integrity verification"
fi

# Extract
log_info "Extracting files..."
tar -xzf "$TMP_DIR/installer.tar.gz" -C "$TMP_DIR"

# Check if install.sh exists in the extracted content
# The TGZ structure should match the control-deploy folder content
if [ ! -f "$TMP_DIR/install.sh" ]; then
    log_error "Invalid installer archive: install.sh not found."
    # Debug info
    echo "Contents of archive:"
    ls -R "$TMP_DIR"
    exit 1
fi

chmod +x "$TMP_DIR/install.sh"

# Execute inner installer with filtered arguments (excluding --keep-sources)
log_info "Launching installer..."
echo ""
"$TMP_DIR/install.sh" "${FILTERED_ARGS[@]}"

# Show location of preserved sources if --keep-sources was used
if [ "$KEEP_SOURCES" -eq 1 ]; then
    echo ""
    log_info "Sources preserved at: ${TMP_DIR}"
    log_info "To manually clean up: rm -rf ${TMP_DIR}"
fi
