#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")"

TAG="${1:-latest}"
export INVENTORY_IMAGE_TAG="$TAG"

# --- Self-update from Docker image ---
# After pulling the new image, extracts this script from it.
# If the version inside the image differs, replaces itself and re-executes.
if [ "${_DEPLOY_UPDATED:-0}" != "1" ]; then
    echo "==> Pulling image..."
    sudo docker compose pull

    SELF="$(realpath "$0")"
    TEMP_SCRIPT="$(mktemp)"
    sudo docker compose run --rm --no-deps -T --entrypoint cat app /var/www/html/infra/prod/deploy.sh > "$TEMP_SCRIPT" 2>/dev/null || true

    if [ -s "$TEMP_SCRIPT" ] && ! diff -q "$SELF" "$TEMP_SCRIPT" > /dev/null 2>&1; then
        echo "==> deploy.sh updated from image, re-executing..."
        cp "$TEMP_SCRIPT" "$SELF"
        chmod +x "$SELF"
        rm -f "$TEMP_SCRIPT"
        export _DEPLOY_UPDATED=1
        exec "$SELF" "$@"
    fi
    rm -f "$TEMP_SCRIPT"
fi

echo "==> Deploying inventory:${TAG}..."

# Fix storage directory structure (one-time migration fix)
# Files were nested under storage/storage/documents/ instead of storage/ directly
if [ -d "storage/storage/documents" ]; then
    echo "==> Fixing storage directory structure..."
    cp -a storage/storage/documents/* storage/ 2>/dev/null || true
    rm -rf storage/storage
    echo "==> Storage structure fixed."
fi

# Ensure storage directory exists with correct ownership
mkdir -p storage
sudo chown -R www-data:www-data storage

echo "==> Enabling maintenance mode..."
touch maintenance.on

# Pull image (skip if already pulled during self-update)
if [ "${_DEPLOY_UPDATED:-0}" != "1" ]; then
    echo "==> Pulling image..."
    sudo docker compose pull
fi

echo "==> Starting container..."
sudo docker compose up -d

echo "==> Waiting for container to be ready..."
sleep 3

echo "==> Extracting maintenance page..."
mkdir -p public
sudo docker compose cp app:/var/www/html/public/maintenance.html public/maintenance.html

echo "==> Running migrations..."
sudo docker compose exec -T -u www-data app php bin/console doctrine:migrations:migrate --no-interaction

echo "==> Clearing cache..."
sudo docker compose exec -T -u www-data app php bin/console cache:clear --env=prod
sudo docker compose exec -T -u www-data app php bin/console cache:warmup --env=prod

echo "==> Disabling maintenance mode..."
rm -f maintenance.on

VERSION=$(sudo docker compose exec -T app cat config/version.yaml | grep 'app.version' | awk -F"'" '{print $2}')
echo "==> Deployed v${VERSION}"
