#!/usr/bin/env bash
# Pre-cache OS Template - Download Ubuntu 22.04 template before deployment
# This saves 5-10 minutes during deployment

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

source "$PROJECT_ROOT/lib/common.sh" 2>/dev/null || {
    # Basic logging if common.sh not available
    log_info() { echo "[INFO] $1"; }
    log_success() { echo "[✓] $1"; }
    log_error() { echo "[ERROR] $1"; exit 1; }
}

# Load configuration
load_config "$PROJECT_ROOT/config/proxmox.conf" 2>/dev/null || true

TEMPLATE_NAME="${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}"
TEMPLATE_FILE="ubuntu-22.04-standard_22.04-1_amd64.tar.zst"

log_info "========================================="
log_info "Pre-cache OS Template"
log_info "========================================="
log_info ""
log_info "Template: $TEMPLATE_NAME"
log_info "File: $TEMPLATE_FILE"
log_info ""

# Check if running on Proxmox host
if ! command_exists pveam; then
    log_error "pveam command not found. This script must be run on Proxmox host."
fi

# Check if template already exists
log_info "Checking if template already exists..."
if pveam list local | grep -q "$TEMPLATE_FILE"; then
    log_success "Template $TEMPLATE_FILE already exists in local storage"
    log_info "No download needed. Deployment will use existing template."
    log_info ""
    log_info "Template details:"
    pveam list local | grep "$TEMPLATE_FILE"
    exit 0
fi

# Check available templates
log_info "Checking available templates..."
if ! pveam available | grep -q "$TEMPLATE_FILE"; then
    log_error "Template $TEMPLATE_FILE not available. Please check template name."
fi

# Download template
log_info "Downloading template $TEMPLATE_FILE..."
log_info "This may take 5-10 minutes depending on network speed..."
log_info ""

if pveam download local "$TEMPLATE_FILE"; then
    log_success "Template downloaded successfully"
    log_info ""
    log_info "Template is now cached and ready for deployment"
    log_info "This saves 5-10 minutes during container creation phase"
    log_info ""
    log_info "Template details:"
    pveam list local | grep "$TEMPLATE_FILE"
else
    log_error "Failed to download template"
fi

