#!/bin/bash
# =============================================================================
# Customer Portal - Image Loader Script for Portainer
# =============================================================================
# Usage: ./update-stack.sh <image-tag>
# Example: ./update-stack.sh 20241201-abc123
#          ./update-stack.sh latest
#
# Note: After loading images, update the stack in Portainer UI
# =============================================================================

set -Eeuo pipefail

# Configuration
IMAGES_DIR="${IMAGES_DIR:-$(pwd)}"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log()  { echo -e "${GREEN}[DEPLOY]${NC} $*"; }
warn() { echo -e "${YELLOW}[DEPLOY]${NC} $*"; }
fail() { echo -e "${RED}[DEPLOY] ERROR:${NC} $*"; exit 1; }

# Check arguments
TAG="${1:-latest}"

echo ""
log "Loading images with tag: ${TAG}"
echo ""

# Look for image files
FRONTEND_TAR="${IMAGES_DIR}/portal-frontend-${TAG}.tar"
BACKEND_TAR="${IMAGES_DIR}/portal-backend-${TAG}.tar"
FRONTEND_TARGZ="${IMAGES_DIR}/portal-frontend-${TAG}.tar.gz"
BACKEND_TARGZ="${IMAGES_DIR}/portal-backend-${TAG}.tar.gz"

# Also check alternative naming
if [[ ! -f "$FRONTEND_TAR" ]]; then
    FRONTEND_TAR="${IMAGES_DIR}/portal-frontend.${TAG}.tar"
fi
if [[ ! -f "$BACKEND_TAR" ]]; then
    BACKEND_TAR="${IMAGES_DIR}/portal-backend.${TAG}.tar"
fi

if [[ ! -f "$FRONTEND_TARGZ" ]]; then
    FRONTEND_TARGZ="${IMAGES_DIR}/portal-frontend.${TAG}.tar.gz"
fi
if [[ ! -f "$BACKEND_TARGZ" ]]; then
    BACKEND_TARGZ="${IMAGES_DIR}/portal-backend.${TAG}.tar.gz"
fi

# Load frontend
if [[ -f "$FRONTEND_TARGZ" ]]; then
    log "Loading frontend image from: $FRONTEND_TARGZ"
    gunzip -c "$FRONTEND_TARGZ" | docker load
elif [[ -f "$FRONTEND_TAR" ]]; then
    log "Loading frontend image from: $FRONTEND_TAR"
    docker load -i "$FRONTEND_TAR"
else
    warn "Frontend tarball not found: $FRONTEND_TAR or $FRONTEND_TARGZ"
fi

# Load backend
if [[ -f "$BACKEND_TARGZ" ]]; then
    log "Loading backend image from: $BACKEND_TARGZ"
    gunzip -c "$BACKEND_TARGZ" | docker load
elif [[ -f "$BACKEND_TAR" ]]; then
    log "Loading backend image from: $BACKEND_TAR"
    docker load -i "$BACKEND_TAR"
else
    warn "Backend tarball not found: $BACKEND_TAR or $BACKEND_TARGZ"
fi

echo ""
log "Current portal images:"
docker images | grep portal || echo "No portal images found"

echo ""
log "Next steps:"
echo "  1. Go to Portainer UI"
echo "  2. Navigate to Stacks → customer-portal"
echo "  3. Update FRONTEND_IMAGE and BACKEND_IMAGE if using specific tag"
echo "  4. Click 'Update the stack' with 'Re-pull image' checked"
echo ""
