#!/bin/bash
set -e

KUBECONFIG=$1
IMAGE=$2

if [ -z "$KUBECONFIG" ] || [ -z "$IMAGE" ]; then
    echo "Usage: $0 <kubeconfig> <image>"
    exit 1
fi

OLD_IMAGE=$(kubectl --kubeconfig $KUBECONFIG get deploy api -o jsonpath='{.spec.template.spec.containers[0].image}' 2>/dev/null)
if [ -z "$OLD_IMAGE" ]; then
    echo "Error: Failed to get old image"
    exit 1
fi

if echo $KUBECONFIG | grep -q "kubeconfig.dev"; then
    EMBLEM_ENV="dev"
else
    EMBLEM_ENV="prod"
fi

curl -X POST https://euphon-alert-23358.famzheng.workers.dev/ -d "Deploying Emblem API to $EMBLEM_ENV: $OLD_IMAGE -> $IMAGE"

kubectl --kubeconfig $KUBECONFIG set image deploy api emblem=$IMAGE
kubectl --kubeconfig $KUBECONFIG rollout status --timeout=1h deploy api