#!/usr/bin/env bash
# Usage: deploy/ci-deploy.sh <core|console> [git-ref]   (default ref: origin/dev)
# Builds karma/<name>:<sha8> from the repo at ref, then blue-green deploys it.
set -euo pipefail
APP=${1:?core|console}; REF=${2:-origin/dev}
REPO=/var/www/vhosts/karma-subito-and-marketing-admin-panel/httpsdocs
cd "$REPO"
git fetch --all
git reset --hard "$REF"
TAG=$(git rev-parse --short=8 HEAD)
case $APP in
  core)    NAME=core2;    DF=deploy/Dockerfile.core;    SECRET=() ;;
  console) NAME=console2; DF=deploy/Dockerfile.console; SECRET=(--secret id=console_env,src=/opt/karma/console2/console.env) ;;
  *) echo "unknown app" >&2; exit 2 ;;
esac
if ! docker image inspect "karma/$NAME:$TAG" >/dev/null 2>&1; then
  DOCKER_BUILDKIT=1 nice -n 10 docker build -f "$DF" "${SECRET[@]}" -t "karma/$NAME:$TAG" .
fi
cd deploy && ./bluegreen.sh "$APP" deploy "$TAG"
