#!/bin/bash
set -euo pipefail

# Version
VERSION="6.2.2-1"
COMMON_TAG="rhel9-6.2.2"

# Images
MARIA_IMAGE="jobarg-server-maria"
MYSQL_IMAGE="jobarg-server-mysql"
PGSQL_IMAGE="jobarg-server-postgres"

# Map images to existing folders
declare -A IMAGE_DIR_MAP=(
    ["${MARIA_IMAGE}:${COMMON_TAG}"]="maria"
    ["${MYSQL_IMAGE}:${COMMON_TAG}"]="mysql"
    ["${PGSQL_IMAGE}:${COMMON_TAG}"]="postgres"
)

echo "Exporting Docker images to existing folders..."

for IMAGE in "${!IMAGE_DIR_MAP[@]}"; do
    DIR="db/${IMAGE_DIR_MAP[$IMAGE]}"

    if [ ! -d "$DIR" ]; then
        echo "Error: Folder $DIR does not exist. Skipping $IMAGE."
        continue
    fi

    if docker image inspect "$IMAGE" >/dev/null 2>&1; then
        # Construct filename as: jobarg-server-<name>-image-<VERSION>.tar.gz
        NAME=$(echo "$IMAGE" | cut -d':' -f1) # strip tag
        FILENAME="${NAME}-image-${VERSION}.tar.gz"
        DEST="$DIR/$FILENAME"

        echo "Exporting $IMAGE -> $DEST..."
        docker save "$IMAGE" | gzip > "$DEST"
        echo "Done: $DEST"
    else
        echo "Warning: Image $IMAGE not found, skipping..."
    fi
done

# List exported files
ls -l ./db/maria ./db/mysql ./db/postgres | grep .tar.gz || true

echo "All *.tar.gz files exported correctly!"