#!/bin/bash
# Full deployment script - bumps both container versions by 0.001 and copies database

DEPLOYMENT_FILE="argocd/deployment.yaml"
DB_SOURCE="data/db.sqlite3"
DB_DEST="data-loader/preload.sqlite3"

# Check if deployment file exists
if [ ! -f "$DEPLOYMENT_FILE" ]; then
    echo "Error: $DEPLOYMENT_FILE not found"
    exit 1
fi

# Check if source database exists
if [ ! -f "$DB_SOURCE" ]; then
    echo "Error: $DB_SOURCE not found"
    exit 1
fi

# Extract current version of data-loader
LOADER_VERSION=$(grep -E "image: git.baumann.gr/adebaumann/vgui-data-loader:[0-9]" "$DEPLOYMENT_FILE" | sed -E 's/.*:([0-9.]+)/\1/')

# Extract current version of main container
MAIN_VERSION=$(grep -E "image: git.baumann.gr/adebaumann/vgui:[0-9]" "$DEPLOYMENT_FILE" | grep -v "data-loader" | sed -E 's/.*:([0-9.]+)/\1/')

if [ -z "$LOADER_VERSION" ] || [ -z "$MAIN_VERSION" ]; then
    echo "Error: Could not find current versions"
    exit 1
fi

# Calculate new versions (add 0.001), preserve leading zero
NEW_LOADER_VERSION=$(echo "$LOADER_VERSION + 0.001" | bc | sed 's/^\./0./')
NEW_MAIN_VERSION=$(echo "$MAIN_VERSION + 0.001" | bc | sed 's/^\./0./')

# Update the deployment file
sed -i "s|image: git.baumann.gr/adebaumann/labhelper-data-loader:$LOADER_VERSION|image: git.baumann.gr/adebaumann/labhelper-data-loader:$NEW_LOADER_VERSION|" "$DEPLOYMENT_FILE"
sed -i "s|image: git.baumann.gr/adebaumann/labhelper:$MAIN_VERSION|image: git.baumann.gr/adebaumann/labhelper:$NEW_MAIN_VERSION|" "$DEPLOYMENT_FILE"

# Update the configmap version to match the main container
CONFIGMAP_FILE="argocd/configmap.yaml"
sed -i "s|VERSION: \"$MAIN_VERSION\"|VERSION: \"$NEW_MAIN_VERSION\"|" "$CONFIGMAP_FILE"

# Copy database
cp "$DB_SOURCE" "$DB_DEST"

echo "Full deployment prepared:"
echo "  Data loader: $LOADER_VERSION -> $NEW_LOADER_VERSION"
echo "  Main container: $MAIN_VERSION -> $NEW_MAIN_VERSION"
echo "  ConfigMap VERSION: $NEW_MAIN_VERSION"
echo "  Database copied to $DB_DEST"
