#!/bin/sh
# Materia Supervisor - Continuous pipeline orchestration
# Inspired by TigerBeetle's CFO supervisor: simple, resilient, easy to understand
# https://github.com/tigerbeetle/tigerbeetle/blob/main/src/scripts/cfo_supervisor.sh

set -eu

readonly REPO_DIR="/opt/materia"

while true
do
    (
        # Clone repo if missing
        if ! [ -d "$REPO_DIR/.git" ]
        then
            echo "Repository not found, bootstrap required!"
            exit 1
        fi

        cd "$REPO_DIR"

        # Update code from git
        git fetch origin master
        git switch --discard-changes --detach origin/master
        uv sync

        # Run pipelines
        LANDING_DIR="${LANDING_DIR:-/data/materia/landing}" \
        DUCKDB_PATH="${DUCKDB_PATH:-/data/materia/lakehouse.duckdb}" \
            uv run materia pipeline run extract

        LANDING_DIR="${LANDING_DIR:-/data/materia/landing}" \
        DUCKDB_PATH="${DUCKDB_PATH:-/data/materia/lakehouse.duckdb}" \
            uv run materia pipeline run transform

    ) || sleep 600  # Sleep 10 min on failure to avoid busy-loop retries
done
