#!/usr/bin/env bash
# ============================================================
# Velocity-OS — ECR Registry Provisioner + Image Push Script
# Assumes: aws cli v2, docker, cosign installed on build host
# Run from the Velocity-OS repo root in CI or locally.
# ============================================================
set -euo pipefail

# ── Configuration ────────────────────────────────────────────
AWS_REGION="${AWS_REGION:-ap-south-1}"
AWS_ACCOUNT_ID="${AWS_ACCOUNT_ID:?Must set AWS_ACCOUNT_ID}"
ECR_REGISTRY="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
REGISTRY_PREFIX="velocity-os"

# Image tags from git (deterministic, immutable)
GIT_SHA=$(git rev-parse --short HEAD)
GIT_TAG=$(git tag --points-at HEAD | head -n1 || echo "")
IMAGE_TAG="${GIT_TAG:-$GIT_SHA}"

SERVICES=("core" "webos" "media-engine" "agents")

# ── Step 1: Provision ECR repositories (idempotent) ──────────
echo "=== Provisioning ECR repositories ==="
for svc in "${SERVICES[@]}"; do
  REPO_NAME="${REGISTRY_PREFIX}/${svc}"
  echo "  Ensuring repo: ${REPO_NAME}"
  aws ecr describe-repositories \
    --repository-names "${REPO_NAME}" \
    --region "${AWS_REGION}" \
    --no-cli-pager \
    > /dev/null 2>&1 || \
  aws ecr create-repository \
    --repository-name "${REPO_NAME}" \
    --region "${AWS_REGION}" \
    --image-scanning-configuration scanOnPush=true \
    --image-tag-mutability IMMUTABLE \
    --encryption-configuration encryptionType=AES256 \
    --no-cli-pager
done

# ── Step 2: ECR Login ─────────────────────────────────────────
echo "=== Authenticating to ECR ==="
aws ecr get-login-password --region "${AWS_REGION}" | \
  docker login --username AWS --password-stdin "${ECR_REGISTRY}"

# ── Step 3: Build + Push + Sign each image ───────────────────
echo "=== Building, pushing, and signing images ==="
for svc in "${SERVICES[@]}"; do
  LOCAL_IMAGE="velocity-os/${svc}:${IMAGE_TAG}"
  REMOTE_IMAGE="${ECR_REGISTRY}/${REGISTRY_PREFIX}/${svc}:${IMAGE_TAG}"
  REMOTE_LATEST="${ECR_REGISTRY}/${REGISTRY_PREFIX}/${svc}:latest"

  echo ""
  echo "--- Service: ${svc} ---"

  # Build
  echo "  Building ${LOCAL_IMAGE}..."
  docker build \
    --cache-from "${REMOTE_LATEST}" \
    --build-arg BUILDKIT_INLINE_CACHE=1 \
    --label "git.sha=${GIT_SHA}" \
    --label "git.tag=${GIT_TAG}" \
    --label "build.date=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    -t "${LOCAL_IMAGE}" \
    -t "${REMOTE_IMAGE}" \
    -t "${REMOTE_LATEST}" \
    "./${svc}"

  # Push (sha-tagged first for immutability, then latest)
  echo "  Pushing ${REMOTE_IMAGE}..."
  docker push "${REMOTE_IMAGE}"
  docker push "${REMOTE_LATEST}"

  # Sign with cosign (Sigstore keyless or KMS key)
  echo "  Signing ${REMOTE_IMAGE} with cosign..."
  IMAGE_DIGEST=$(docker inspect --format='{{index .RepoDigests 0}}' "${REMOTE_IMAGE}" || \
    aws ecr describe-images \
      --repository-name "${REGISTRY_PREFIX}/${svc}" \
      --image-ids imageTag="${IMAGE_TAG}" \
      --region "${AWS_REGION}" \
      --query 'imageDetails[0].imageDigest' \
      --output text)
  cosign sign --yes "${ECR_REGISTRY}/${REGISTRY_PREFIX}/${svc}@${IMAGE_DIGEST}"

  echo "  ✓ ${svc} pushed and signed: ${REMOTE_IMAGE}"
done

echo ""
echo "=== All images built, pushed, and signed. ==="
echo "ECR Registry: ${ECR_REGISTRY}"
echo "Image tag: ${IMAGE_TAG}"
