#!/usr/bin/env bash

set -e

DB_PATH="/4server/data/contracts.db"
COMPOSE_FILE="/4server/docker-compose.yml"
START_CONTAINER="/4server/sbin/startContainer"

echo "$(date '+%Y-%m-%d %H:%M:%S') Stopping and removing all Docker containers..."

# Remove all containers, including running containers
containers=$(doas docker ps -a -q)

if [ -n "$containers" ]; then
    doas docker rm -f $containers
else
    echo "No containers to remove."
fi

echo "$(date '+%Y-%m-%d %H:%M:%S') Starting infrastructure..."

# Start infrastructure
doas docker compose -f "$COMPOSE_FILE" up -d

echo "$(date '+%Y-%m-%d %H:%M:%S') Infrastructure started."

# Get all non-expired container UUIDs
echo "$(date '+%Y-%m-%d %H:%M:%S') Loading active containers from database..."

uuids=$(sqlite3 "$DB_PATH" "
    SELECT UUID
    FROM containers
    WHERE expires > date('now');
")

# Start each active container
for uuid in $uuids; do
    echo "$(date '+%Y-%m-%d %H:%M:%S') Starting $uuid"

    "$START_CONTAINER" "$uuid"
done

echo "$(date '+%Y-%m-%d %H:%M:%S') Restart complete."
