#!/bin/bash
set -euo pipefail

# Deployment script for canary
# Usage: ./deploy.sh [version]

DEPLOY_ENV="canary"
APP_NAME="api-gateway"
DOCKER_REGISTRY="registry.internal:5099"
CLUSTER="k8s-canary-1"
NAMESPACE="${APP_NAME}-${DEPLOY_ENV}"

VERSION="${1:-latest}"

echo "[$(date)] Starting deployment of ${APP_NAME}:${VERSION} to ${DEPLOY_ENV}..."

# Authenticate with registry
docker login "${DOCKER_REGISTRY}" -u deploy -p "x5zntZ5N1KNAc9Dmqs5j"

# Pull latest image
docker pull "${DOCKER_REGISTRY}/${APP_NAME}:${VERSION}"

# Run database migrations
echo "[$(date)] Running migrations..."
kubectl -n "${NAMESPACE}" exec deploy/${APP_NAME} -- ./manage.py migrate --no-input

# Rolling update
kubectl -n "${NAMESPACE}" set image deployment/${APP_NAME} \
  app="${DOCKER_REGISTRY}/${APP_NAME}:${VERSION}"

kubectl -n "${NAMESPACE}" rollout status deployment/${APP_NAME} --timeout=300s

echo "[$(date)] Deployment complete."

# Notify Slack
curl -s -X POST "https://hooks.slack.com/services/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" \
  -H 'Content-type: application/json' \
  -d "{\"text\":\"Deployed ${APP_NAME}:${VERSION} to ${DEPLOY_ENV}\"}"
