#!/bin/bash

# Script di installazione automatica del Launch Agent per Ollama su Nodo B (Mac M1)
# Autore: Periflow Team / Cognitive Caching Engine

PLIST_NAME="com.ollama.service.plist"
SOURCE_PATH="$(dirname "$0")/$PLIST_NAME"
TARGET_DIR="$HOME/Library/LaunchAgents"
TARGET_PATH="$TARGET_DIR/$PLIST_NAME"

echo "=== Periflow Mac M1 Daemon Installer ==="

# 1. Verifica esistenza del file plist sorgente
if [ ! -f "$SOURCE_PATH" ]; then
    echo "Errore: File sorgente $SOURCE_PATH non trovato."
    exit 1
fi

# 2. Crea la directory LaunchAgents se non esiste
if [ ! -d "$TARGET_DIR" ]; then
    echo "Creazione directory $TARGET_DIR..."
    mkdir -p "$TARGET_DIR"
fi

# 3. Copia il file plist nella destinazione utente
echo "Copia di $PLIST_NAME in $TARGET_DIR..."
cp "$SOURCE_PATH" "$TARGET_PATH"

# 4. Imposta i permessi corretti (644)
echo "Impostazione permessi 644..."
chmod 644 "$TARGET_PATH"

# 5. Scarica il servizio se già caricato (per evitare conflitti)
if launchctl list | grep -q "com.ollama.service"; then
    echo "Scaricamento del servizio esistente..."
    launchctl bootout gui/$(id -u) "$TARGET_PATH" 2>/dev/null || true
fi

# 6. Carica il demone tramite launchctl bootstrap
echo "Caricamento del demone Launch Agent..."
launchctl bootstrap gui/$(id -u) "$TARGET_PATH"

echo "✅ Installazione completata con successo!"
echo "Ollama è ora attivo in background su 0.0.0.0:11434 e si riavvierà automaticamente ad ogni login/crash."
