#!/bin/bash

# Check that a search string was provided
if [ -z "$1" ]; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') Usage: $0 <search_string>"
    exit 1
fi

SEARCH="$1"
DB_PATH="/4server/data/contracts.db"

# Get all container_ids where tags include the search string
container_ids=$(sqlite3 "$DB_PATH" "SELECT UUID FROM containers WHERE tags LIKE '%$SEARCH%';")

# Loop through each container_id
for container_id in $container_ids; do
    # Check if a container with this name is running
    if doas docker ps --format '{{.Names}}' | grep -qx "$container_id"; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') Restarting $container_id"
        "$(dirname "$(realpath "${BASH_SOURCE[0]:-$0}")")/startContainer" "$container_id"
    fi
done
