#!/bin/bash
# Builds and pushes a sandbox image for production, then pins the version in the prod config.
# Usage: bin/bump-sandbox [sidecar]   (pass "sidecar" to also bump lifecycle-sidecar)
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
REMOTE=${REMOTE:-git.dxod.org/dexorder/dexorder}
PROD_CONFIG="$ROOT_DIR/deploy/k8s/prod/configs/gateway-config.yaml"

bump() {
    local project="$1"
    echo "==> Building $project..."
    "$SCRIPT_DIR/build" "$project"
    TAG="$(cd "$ROOT_DIR/$project" && git log --oneline | head -1 | cut -d ' ' -f 1)"
    local image="$REMOTE/ai-$project:$TAG"
    echo "==> Pushing $image..."
    docker push "$image"
    docker push "$REMOTE/ai-$project:latest"
    echo "==> Updating prod config: $project → $TAG"
    case "$project" in
        sandbox)
            sed -i "s|sandbox_image: .*|sandbox_image: $image|" "$PROD_CONFIG"
            ;;
        lifecycle-sidecar)
            sed -i "s|sidecar_image: .*|sidecar_image: $image|" "$PROD_CONFIG"
            ;;
    esac
}

bump sandbox
if [ "${1:-}" == "sidecar" ]; then
    bump lifecycle-sidecar
fi

echo ""
echo "Done. Review and commit the config change:"
echo "  git diff $PROD_CONFIG"
echo "  git add $PROD_CONFIG && git commit -m 'bump sandbox'"
echo "  bin/dev restart gateway   # run with --context=prod or equivalent"
