#!/bin/bash
# Build and optionally deploy a service
# Usage: ./scripts/build.sh <service> [--deploy] [version]
# Example: ./scripts/build.sh depot --deploy v1

set -e

SERVICE=${1:-gateway}
DEPLOY=${2:-}
VERSION=${3:-v1}
REGISTRY="localhost:32000"
TAG="$VERSION"

echo "Building $SERVICE..."
docker build --platform linux/arm64 \
  --build-arg SERVICE=$SERVICE \
  -t $REGISTRY/$SERVICE:$TAG \
  -f Dockerfile .

if [ "$DEPLOY" == "--deploy" ]; then
  echo "Saving image..."
  docker save $REGISTRY/$SERVICE:$TAG -o /tmp/$SERVICE.tar
  
  echo "Transferring to cluster..."
  scp /tmp/$SERVICE.tar admin@control-plane.local:/tmp/
  
  echo "Importing to microk8s..."
  ssh admin@control-plane.local "/usr/local/bin/multipass transfer /tmp/$SERVICE.tar microk8s-vm:/tmp/"
  ssh admin@control-plane.local "/usr/local/bin/multipass exec microk8s-vm -- microk8s ctr images rm $REGISTRY/$SERVICE:$TAG 2>/dev/null || true"
  ssh admin@control-plane.local "/usr/local/bin/multipass exec microk8s-vm -- microk8s ctr images import /tmp/$SERVICE.tar"
  
  echo "Restarting deployment..."
  ssh admin@control-plane.local "/usr/local/bin/multipass exec microk8s-vm -- microk8s kubectl rollout restart deployment/$SERVICE -n cloud-services"
  
  echo "Done!"
fi
