#!/bin/sh
# ZendureEvGuard — installation as a systemd service (Linux)
#
# Run it from the folder you unzipped, as root:   sudo ./install-linux.sh
#
# It installs the daemon FROM THE CURRENT FOLDER: nothing is copied elsewhere, so the folder you
# unzipped is the folder that runs. Re-running it upgrades the service in place.
set -eu

SERVICE_NAME="zendure-evguard"
UNIT="/etc/systemd/system/${SERVICE_NAME}.service"
DIR="$(cd "$(dirname "$0")" && pwd)"
EXE="${DIR}/ZendureEvGuard"

[ "$(id -u)" -eq 0 ] || { echo "This installer must run as root: sudo ./install-linux.sh" >&2; exit 1; }
[ -f "$EXE" ] || { echo "ZendureEvGuard not found next to this script (looked in ${DIR})." >&2; exit 1; }
command -v systemctl >/dev/null 2>&1 || { echo "systemd not found. See USER_GUIDE_EN.md to run it manually." >&2; exit 1; }

chmod +x "$EXE"

# The settings file is the user's, never ours. An upgrade that overwrote it would wipe the meter
# address, the licence key and every notification credential in one go.
if [ -f "${DIR}/appsettings.json" ]; then
    echo "Keeping your existing appsettings.json (not overwritten)."
else
    echo "WARNING: no appsettings.json found. The daemon will refuse to start until you create one."
fi

if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
    echo "Stopping the running service..."
    # The daemon puts the battery back into service on shutdown; give it the time to finish.
    systemctl stop "$SERVICE_NAME" || true
fi

echo "Writing ${UNIT}..."
cat > "$UNIT" <<UNITFILE
[Unit]
Description=ZendureEvGuard - EV Charging Battery Protection Daemon
# network-online.target, not network.target: the latter is reached as soon as the stack is
# configured, before an address is actually up. The first probes of the meter and of the hub
# then fail at every boot, and the daemon opens on a precautionary pause it has to walk back.
Wants=network-online.target
After=network-online.target

[Service]
Type=simple
# WorkingDirectory SANS guillemets, ExecStart AVEC : systemd ne déquote QUE les réglages à liste.
# Des guillemets sur WorkingDirectory donnent `path is not absolute: "/tmp"` et l'unité refuse de
# se charger — vérifié par `systemd-analyze verify`. Un chemin contenant une espace est déjà pris
# en entier par WorkingDirectory ; c'est ExecStart, découpé en arguments, qui en a besoin.
WorkingDirectory=${DIR}
ExecStart="${EXE}"
# on-failure and NOT always: the daemon exits with code 0 when it refuses to start on a bad
# setting, precisely so systemd does not restart it every ten seconds for a fault no restart
# can fix. "always" would turn a typo into an endless loop of crash mails.
Restart=on-failure
RestartSec=10
# On stop the daemon puts the battery back into service. systemd must outlast that work,
# otherwise it SIGKILLs mid-restore and the hub stays paused until the next start. This value
# is coupled with the daemon's own 60s shutdown budget: raising one without the other
# re-creates the blockage.
TimeoutStopSec=120
SyslogIdentifier=${SERVICE_NAME}
Environment=DOTNET_ENVIRONMENT=Production

[Install]
WantedBy=multi-user.target
UNITFILE

systemctl daemon-reload
systemctl enable "$SERVICE_NAME" >/dev/null 2>&1 || true
systemctl start "$SERVICE_NAME"
sleep 3

if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo ""
    echo "ZendureEvGuard is installed and running."
    echo "  status : systemctl status ${SERVICE_NAME}"
    echo "  logs   : journalctl -u ${SERVICE_NAME} -f     (or ${DIR}/logs/)"
    echo "  stop   : systemctl stop ${SERVICE_NAME}"
else
    echo ""
    echo "The service did not stay up. Read why with:" >&2
    echo "  journalctl -u ${SERVICE_NAME} -n 50 --no-pager" >&2
    exit 1
fi
