#!/bin/bash
# Entrypoint personnalisé pour Everest Manager - Cariflex
# Configure l'OCPP CSMS URL puis lance le simulateur

set -e

CSMS_URL="${EVEREST_TARGET_URL:-ws://cariflex-citrineos-server:8080/cp001}"
echo "=== EVerest Manager - Cariflex ==="
echo "CSMS URL: $CSMS_URL"

# Installer sqlite3 si nécessaire
apk add --no-cache sqlite3 2>/dev/null || true

# Configurer l'OCPP CSMS URL dans la base de données
DB_PATH="/ext/source/build/dist/share/everest/modules/OCPP201/device_model_storage.db"
if [ -f "$DB_PATH" ]; then
    echo "Configuring OCPP CSMS URL in device model DB..."
    sqlite3 "$DB_PATH" "UPDATE VARIABLE_ATTRIBUTE SET value = '[{\"configurationSlot\": 1, \"connectionData\": {\"messageTimeout\": 30, \"ocppCsmsUrl\": \"$CSMS_URL\", \"ocppInterface\": \"Wired0\", \"ocppTransport\": \"JSON\", \"ocppVersion\": \"OCPP20\", \"securityProfile\": 1}}]' WHERE variable_Id IN (SELECT id FROM VARIABLE WHERE name = 'NetworkConnectionProfiles');"
    echo "OCPP CSMS URL configured."
else
    echo "WARNING: device_model_storage.db not found at $DB_PATH"
fi

# Installer http-server pour les logs
npm i -g http-server 2>/dev/null || true

# Lancer le simulateur OCPP 2.0.1 avec PNC (Plug & Charge)
echo "Starting EVerest OCPP 2.0.1 simulator..."
chmod +x /ext/source/build/run-scripts/run-sil-ocpp201-pnc.sh
exec /ext/source/build/run-scripts/run-sil-ocpp201-pnc.sh
