#!/bin/sh /etc/rc.common
# Copyright (c) 2026 Luis Rosales - MIT License
#
# Starts the Lua event forwarder and exports UCI config to the environment
# so that /etc/hotplug.d/{wireless,dhcp}/* scripts can read SERVER_URL, etc.

START=95
STOP=10
NAME=client2server
STATE_DIR="/var/run/${NAME}"
PIDFILE="${STATE_DIR}/pid"
ENV_FILE="${STATE_DIR}/env"

start() {
    logger -t "$NAME" -p user.info "Starting $NAME..."

    # Check config
    if [ ! -f /etc/config/client2server ]; then
        logger -t "$NAME" -p user.err "Config not found"
        exit 1
    fi

    # Ensure state dir exists (shared with hotplug scripts)
    mkdir -p "$STATE_DIR"
    chmod 0755 "$STATE_DIR"

    # Check if enabled
    local enabled
    enabled=$(uci get client2server.general.enabled 2>/dev/null)
    if [ "$enabled" = "0" ]; then
        logger -t "$NAME" -p user.info "Disabled in config"
        exit 0
    fi

    # Read UCI into environment file (so hotplug scripts can inherit it)
    local server_url token router_id
    server_url=$(uci get client2server.server.url 2>/dev/null)
    token=$(uci get client2server.server.token 2>/dev/null)
    router_id=$(uci get client2server.router.id 2>/dev/null)
    if [ -z "$router_id" ]; then
        router_id=$(cat /proc/sys/kernel/hostname 2>/dev/null || echo unknown)
    fi

    cat > "$ENV_FILE" <<EOF
SERVER_URL='${server_url}'
TOKEN='${token}'
ROUTER_ID='${router_id}'
EOF
    chmod 0640 "$ENV_FILE"

    # Make sure Lua script is executable
    chmod +x /usr/sbin/client2server-unified.lua 2>/dev/null

    # Start the Lua script with UCI env exported (and load env file for any
    # child processes that need it - e.g. hotplug scripts forked by netifd)
    logger -t "$NAME" -p user.info "router_id=$router_id url=$server_url"

    # shellcheck disable=SC1090
    set -a
    . "$ENV_FILE"
    set +a
    lua /usr/sbin/client2server-unified.lua &
    echo $! > $PIDFILE

    logger -t "$NAME" -p user.info "Started with PID $(cat $PIDFILE)"
}

stop() {
    if [ -f $PIDFILE ]; then
        local pid
        pid=$(cat $PIDFILE)
        kill -TERM "$pid" 2>/dev/null
        rm -f $PIDFILE
    fi
    rm -f "$ENV_FILE" 2>/dev/null
    # NOTE: keep STATE_DIR and buffer file across restarts so queued
    # events survive an agent restart. They live in /var/run (tmpfs),
    # so they will still be lost on reboot - which is acceptable since
    # the events are transient network events.
    logger -t "$NAME" -p user.info "Stopped"
}

reload() {
    stop
    sleep 1
    start
}
