#!/usr/bin/env bash
set -euo pipefail

OSAET_ROOT="${OSAET_ROOT:-/opt/osaet}"
APP_DIR="${OSAET_APP_DIR:-$OSAET_ROOT/app}"
BIN_DIR="${OSAET_BIN_DIR:-$OSAET_ROOT/bin}"
SERVICE_NAME="${OSAET_SERVICE_NAME:-osaet-admin}"

export OSAET_REPO_ROOT="${OSAET_REPO_ROOT:-$APP_DIR}"
export OSAET_LOCAL_CONFIG="${OSAET_LOCAL_CONFIG:-$OSAET_ROOT/config/local.yaml}"

cd "$APP_DIR"
git fetch origin main
git checkout main
git pull --ff-only origin main

cd "$APP_DIR/frontend/admin"
npm ci
npm run build

cd "$APP_DIR/frontend/site"
npm ci
npm run build

mkdir -p "$BIN_DIR"
cd "$APP_DIR/backend"
go test ./...
go build -o "$BIN_DIR/osaet-admin" ./cmd/osaet-admin

"$BIN_DIR/osaet-admin" migrate

sudo systemctl restart "$SERVICE_NAME"
sudo systemctl --no-pager --lines=20 status "$SERVICE_NAME"
