#!/bin/sh
set -eu

DOCKER=/usr/local/bin/docker
SRC=/volume1/docker/nodedc-platform/tasker/plane-src
APP=/volume1/docker/nodedc-platform/tasker/plane-app
BUILD_BACKEND=${BUILD_BACKEND:-1}
BUILD_WEB=${BUILD_WEB:-1}
BUILD_ADMIN=${BUILD_ADMIN:-0}
RECREATE_SERVICES=""

printf "== sudo session ==\n"
sudo -v

if [ "$BUILD_BACKEND" = "1" ]; then
  printf "== backend image: nodedc/plane-backend:local ==\n"
  cd "$SRC/apps/api"
  sudo DOCKER_BUILDKIT=0 "$DOCKER" build \
    -t nodedc/plane-backend:local \
    -f Dockerfile.api .
  RECREATE_SERVICES="$RECREATE_SERVICES api worker beat-worker"
else
  printf "== skip backend image ==\n"
fi

if [ "$BUILD_WEB" = "1" ]; then
  printf "== frontend image: nodedc/plane-frontend:ru ==\n"
  cd "$SRC"
  sudo DOCKER_BUILDKIT=0 "$DOCKER" build \
    --build-arg VITE_NODEDC_LAUNCHER_URL=https://hub.nodedc.ru \
    --build-arg VITE_NODEDC_OIDC_LOGIN_ENABLED=1 \
    -t nodedc/plane-frontend:ru \
    -f apps/web/Dockerfile.web.nas-legacy .
  RECREATE_SERVICES="$RECREATE_SERVICES web"
else
  printf "== skip frontend image ==\n"
fi

if [ "$BUILD_ADMIN" = "1" ]; then
  printf "== admin image: nodedc/plane-admin:ru ==\n"
  cd "$SRC"
  sudo DOCKER_BUILDKIT=1 "$DOCKER" build \
    --build-arg VITE_NODEDC_LAUNCHER_URL=https://hub.nodedc.ru \
    -t nodedc/plane-admin:ru \
    -f apps/admin/Dockerfile.admin .
  RECREATE_SERVICES="$RECREATE_SERVICES admin"
else
  printf "== skip admin image ==\n"
fi

if [ -z "$RECREATE_SERVICES" ]; then
  printf "== nothing to recreate ==\n"
  exit 0
fi

printf "== recreate tasker services ==\n"
cd "$APP"
sudo "$DOCKER" compose -p nodedc-tasker \
  --env-file .env.synology \
  -f docker-compose.yaml \
  -f docker-compose.synology.override.yml \
  up -d --no-build --force-recreate $RECREATE_SERVICES

printf "== containers ==\n"
sudo "$DOCKER" ps \
  --filter "name=nodedc-tasker" \
  --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

printf "== smoke: logo ==\n"
curl -k -sSI --resolve ops.nodedc.ru:443:127.0.0.1 \
  https://ops.nodedc.ru/nodedc-logo.svg \
  | grep -Ei "HTTP/|content-type" || true

printf "== smoke: websocket ==\n"
curl -k -i --http1.1 --resolve ops.nodedc.ru:443:127.0.0.1 \
  -H "Connection: Upgrade" \
  -H "Upgrade: websocket" \
  -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
  -H "Sec-WebSocket-Version: 13" \
  https://ops.nodedc.ru/live/nodedc/stream \
  --max-time 35 \
  2>/dev/null | sed -n "1,25p" || true

printf "== done ==\n"
