#!/bin/bash
# Usage: ./start_by_uuid.sh <uuid>
# Example: ./start_by_uuid.sh abc-001-xxxx-xxxx-xxxx
exec > /4server/data/log/startContainer.log 2>&1
echo "$(date '+%Y-%m-%d %H:%M:%S') Start container $1"

source /4server/sbin/helpers

BIN_PATH="/4server/sbin"

UUID="$1"

if [[ -z "$UUID" ]]; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') Usage: $0 <uuid>"
    exit 1
fi

if [[ ! "$UUID" =~ ^[0-9a-fA-F-]+$ ]]; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') ERROR: Invalid UUID format: $UUID"
    exit 1
fi


DOMAIN_FILE="/4server/data/$UUID/etc/domain"
DB_FILE="/4server/data/contracts.db"
if [ -f "$DOMAIN_FILE" ]; then
    DOMAINS=$(paste -sd "," "$DOMAIN_FILE")
    # Escape single quotes for SQLite ('' is the standard SQLite escape for ')
    DOMAINS_SAFE="${DOMAINS//\'/\'\'}"
    UUID_SAFE="${UUID//\'/\'\'}"
    sqlite3 "$DB_FILE" "UPDATE containers SET domains='$DOMAINS_SAFE' WHERE UUID='$UUID_SAFE';"
fi



get_contract_info

# Extract the second part of UUID (split by "-")
SECOND_PART=$(echo "$UUID" | cut -d'-' -f2)

# Decide which script to run
case "$SECOND_PART" in
    001)
        "$BIN_PATH/start/n8n"
        ;;
    002)
        "$BIN_PATH/start/ODOO_18"
        ;;


    003)
        "$BIN_PATH/start/ODOO_19"
        ;;

    004)
        "$BIN_PATH/start/ODOO_17"
        ;;



    *)
        echo "$(date '+%Y-%m-%d %H:%M:%S') Unknown UUID type: $SECOND_PART"
        exit 2
        ;;
esac
