#!/bin/bash
# =============================================================
# Startup script per macless-haystack endpoint
# Risolve il problema della perdita di auth al riavvio Docker
# 
# ROOT CAUSE: pypush_gsa_icloud.py genera USER_ID e DEVICE_ID
# casuali ad ogni avvio. Questo invalida il searchPartyToken.
#
# FIX: Persistiamo gli UUID nel volume /app/endpoint/data/
# e li ricarichiamo ad ogni avvio.
# =============================================================

DATA_DIR="/app/endpoint/data"
UUID_FILE="${DATA_DIR}/persistent_uuids.json"
TARGET_FILE="/app/endpoint/register/pypush_gsa_icloud.py"

echo "[startup] $(date) - Starting macless-haystack endpoint with UUID persistence fix"

# 1. Esegui git pull (updateRepo originale)
if [ -f /app/endpoint/updateRepo ]; then
    echo "[startup] Running updateRepo (git pull)..."
    /app/endpoint/updateRepo 2>&1 || echo "[startup] updateRepo failed, continuing with existing code"
fi

# 2. Patcha pypush_gsa_icloud.py per persistere gli UUID
if [ -f "$TARGET_FILE" ]; then
    echo "[startup] Patching pypush_gsa_icloud.py for UUID persistence..."
    
    # Crea il codice di persistenza UUID
    PATCH_CODE='
import os as _os
import json as _json

def _load_or_create_uuid(name, uuid_file="'"${UUID_FILE}"'"):
    """Load UUID from persistent storage or create and save a new one."""
    data = {}
    if _os.path.exists(uuid_file):
        try:
            with open(uuid_file, "r") as f:
                data = _json.load(f)
        except Exception:
            data = {}
    if name in data:
        return uuid.UUID(data[name])
    new_id = uuid.uuid4()
    data[name] = str(new_id)
    try:
        with open(uuid_file, "w") as f:
            _json.dump(data, f, indent=2)
    except Exception as e:
        print(f"[UUID-FIX] Warning: could not save UUID: {e}")
    return new_id

# Persistent UUIDs - survive container restarts
USER_ID = _load_or_create_uuid("user_id")
DEVICE_ID = _load_or_create_uuid("device_id")
'

    # Controlla se il patch è già stato applicato
    if grep -q "_load_or_create_uuid" "$TARGET_FILE"; then
        echo "[startup] UUID persistence patch already applied"
    else
        # Sostituisci le righe USER_ID e DEVICE_ID con il codice persistente
        # Prima rimuoviamo le righe originali
        sed -i '/^USER_ID = uuid\.uuid4()/d' "$TARGET_FILE"
        sed -i '/^DEVICE_ID = uuid\.uuid4()/d' "$TARGET_FILE"
        sed -i '/^# Created here so that it is consistent/d' "$TARGET_FILE"
        
        # Poi inseriamo il codice di persistenza dopo l'import di uuid
        # Troviamo l'ultima riga di import e aggiungiamo dopo
        LAST_IMPORT_LINE=$(grep -n "^from\|^import" "$TARGET_FILE" | tail -1 | cut -d: -f1)
        
        if [ -n "$LAST_IMPORT_LINE" ]; then
            # Scrivi il codice in un file temporaneo
            TEMP_PATCH=$(mktemp)
            echo "$PATCH_CODE" > "$TEMP_PATCH"
            
            # Inserisci dopo l'ultima riga di import
            sed -i "${LAST_IMPORT_LINE}r ${TEMP_PATCH}" "$TARGET_FILE"
            rm -f "$TEMP_PATCH"
            
            echo "[startup] UUID persistence patch applied successfully"
            
            # Mostra gli UUID che verranno usati
            if [ -f "$UUID_FILE" ]; then
                echo "[startup] Persistent UUIDs: $(cat "$UUID_FILE")"
            fi
        else
            echo "[startup] WARNING: Could not find import lines to patch"
        fi
    fi
else
    echo "[startup] WARNING: Target file not found: $TARGET_FILE"
fi

# 3. Avvia il server endpoint
echo "[startup] Starting endpoint server..."
exec python -u /app/endpoint/mh_endpoint.py
