#!/bin/sh
# camcfg - view and change every camera setting over SSH. Changes persist across reboots
# AND firmware updates: only your overrides are stored (/data/camcfg.conf, "section.key=value"),
# merged over the image defaults (/usr/local/rtsp.ini) at boot and on every change.
#
#   camcfg show [section]           effective settings (* = changed by you)
#   camcfg get KEY                  e.g. camcfg get main.bitrate
#   camcfg set KEY=VALUE ...        validate, save, apply (restarts the stream ~5 s)
#   camcfg unset KEY ...            back to the image default
#   camcfg reset                    drop ALL overrides
#   camcfg keys                     list every key with its allowed values
#   camcfg export                   print your overrides (copy/paste to another camera)
#   camcfg wifi SSID PASSWORD [now] change Wi-Fi (same as wifi-set)
#   camcfg password                 change the root (SSH) password
#   camcfg apply                    rebuild the running config and restart the stream
#   camcfg status                   IP, Wi-Fi signal, stream/recorder state, SD usage
# Options: -n = save only, don't restart the stream.
#
# Shortcuts: main.* = video0.*, sub.* = video1.*,
#   main.bitrate (kbps), main.codec (h264|h265), main.resolution (WxH), main.fps, main.level
#   rtsp.user / rtsp.password / rtsp.port, record.* , system.timezone / system.ntp

BASE=/usr/local/rtsp.ini
OVR=/data/camcfg.conf
LIVE=/etc/config/rtsp.ini
ONVIF_BASE=/usr/local/onvif/onvif.conf
ONVIF_LIVE=/data/onvif.conf
TZF=/data/timezone
NTPF=/data/ntp_server
PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin

die() { echo "camcfg: $*" >&2; exit 1; }

# ---------- key normalisation: shortcut -> section.key (resolution expands to 2) ----------
norm() {
    k=$1
    case "$k" in
        main.*) k=video0.${k#main.} ;;
        sub.*)  k=video1.${k#sub.} ;;
        rtsp.user|rtsp.password) k=auth.${k#rtsp.} ;;
        rtsp.port) k=server.port ;;
    esac
    case "$k" in
        video[01].bitrate) k=${k%.*}.target_kbps ;;
        video[01].codec)   k=${k%.*}.code_type ;;
        video[01].level)   k=${k%.*}.enc_level ;;
    esac
    echo "$k"
}

# ---------- validation: prints normalised value or fails ----------
is_int() { case "$1" in ''|*[!0-9]*) return 1;; esac; return 0; }
range() { is_int "$1" && [ "$1" -ge "$2" ] && [ "$1" -le "$3" ] || die "$KEY must be a number $2..$3 (got '$1')"; echo "$1"; }

validate() {   # $1 = section.key  $2 = value
    KEY=$1; v=$2
    case "$1" in
        video[01].code_type)
            case "$v" in h264|h.264|H264|avc) echo h.264;; h265|h.265|H265|hevc) echo h.265;;
                *) die "$KEY: h264 or h265";; esac ;;
        video0.width)  range "$v" 320 2304 ;;
        video0.height) range "$v" 180 1296 ;;
        video1.width)  range "$v" 160 1280 ;;
        video1.height) range "$v" 90 720 ;;
        video[01].fps) range "$v" 1 25 ;;
        video0.target_kbps) range "$v" 256 16000 ;;
        video1.target_kbps) range "$v" 64 4000 ;;
        video[01].enc_level) range "$v" 10 62 ;;
        auth.user)
            case "$v" in *[!A-Za-z0-9._-]*) die "rtsp.user: letters, digits, . _ - only (empty = no auth)";; esac; echo "$v" ;;
        auth.password)
            case "$v" in *[\ \;\#=\\]*) die "rtsp.password: no spaces, ; # = or backslash";; esac
            [ ${#v} -ge 4 ] || die "rtsp.password: at least 4 characters"; echo "$v" ;;
        server.port) range "$v" 1 65535 ;;
        audio.code_type) case "$v" in aac|g711a|g711u) echo "$v";; *) die "audio.code_type: aac|g711a|g711u";; esac ;;
        audio.sample_rate) case "$v" in 8000|16000) echo "$v";; *) die "audio.sample_rate: 8000|16000";; esac ;;
        record.mode) case "$v" in off|continuous|motion|both) echo "$v";; *) die "record.mode: off|continuous|motion|both";; esac ;;
        record.stream) case "$v" in 0|main) echo 0;; 1|sub) echo 1;; *) die "record.stream: 0/main or 1/sub";; esac ;;
        record.continuous_path|record.motion_path)
            case "$v" in /mnt/*) echo "$v";; *) die "$KEY must be under /mnt (the SD card)";; esac ;;
        record.continuous_percent|record.motion_percent) range "$v" 0 100 ;;
        record.continuous_max_mb|record.motion_max_mb) range "$v" 0 2000000 ;;
        record.min_free_mb) range "$v" 0 100000 ;;
        record.segment_seconds) range "$v" 10 3600 ;;
        record.motion_pre_seconds) range "$v" 0 15 ;;
        record.motion_post_seconds) range "$v" 1 600 ;;
        record.motion_clip_max_seconds) range "$v" 10 3600 ;;
        record.motion_sensitivity) range "$v" 0 100 ;;
        record.motion_threshold) range "$v" 0 65535 ;;
        record.motion_min_cells) range "$v" 1 768 ;;
        record.motion_trigger_frames) range "$v" 1 100 ;;
        record.motion_debug) case "$v" in 0|1) echo "$v";; *) die "record.motion_debug: 0|1";; esac ;;
        record.motion_hook) echo "$v" ;;
        record.queue_max_kb) range "$v" 512 16384 ;;
        system.timezone)
            case "$v" in *[\ \;\#]*|'') die "system.timezone: POSIX TZ string, e.g. UTC0 or CET-1CEST,M3.5.0,M10.5.0/3";; esac; echo "$v" ;;
        system.ntp) case "$v" in *[\ \;\#]*|'') die "system.ntp: a host name";; esac; echo "$v" ;;
        *) die "unknown key '$1' (see: camcfg keys)" ;;
    esac
}

# ---------- ini helpers (awk; values may contain anything but newline) ----------
ini_get() {   # file section key
    awk -v s="[$2]" -v k="$3" '
        /^[ \t]*\[/ { sec=$0; gsub(/[ \t]/,"",sec); next }
        sec==s && $0 ~ "^[ \t]*" k "[ \t]*=" { sub(/^[^=]*=[ \t]*/,""); sub(/[ \t\r]+$/,""); print; exit }' "$1"
}

ini_set() {   # file section key value  (in place; adds key/section if missing)
    awk -v s="[$2]" -v k="$3" -v v="$4" '
        function out() { if (insec && !done) { print k " = " v; done=1 } }
        /^[ \t]*\[/ { t=$0; gsub(/[ \t]/,"",t); if (insec && t!=s) out(); insec=(t==s); if (insec) seen=1; print; next }
        insec && $0 ~ "^[ \t]*" k "[ \t]*=" { if (!done) print k " = " v; done=1; next }
        { print }
        END { if (insec) out(); if (!seen) { print ""; print s; print k " = " v } }' "$1" > "$1.tmp" && mv -f "$1.tmp" "$1"
}

ovr_get() { [ -f "$OVR" ] && sed -n "s/^$(echo "$1" | sed 's/\./\\./')=//p" "$OVR" | tail -1; }
ovr_has() { [ -f "$OVR" ] && grep -q "^$(echo "$1" | sed 's/\./\\./')=" "$OVR"; }
ovr_put() {
    touch "$OVR"; grep -v "^$(echo "$1" | sed 's/\./\\./')=" "$OVR" > "$OVR.tmp"
    [ -n "$3" ] || echo "$1=$2" >> "$OVR.tmp"
    mv -f "$OVR.tmp" "$OVR"
}

# effective value: system.* from files, rest from the merged live ini
eff() {
    case "$1" in
        system.timezone) cat "$TZF" 2>/dev/null || cat /usr/local/timezone 2>/dev/null || echo UTC0 ;;
        system.ntp) cat "$NTPF" 2>/dev/null || echo pool.ntp.org ;;
        *) build_tmp; ini_get "$TMPINI" "${1%%.*}" "${1#*.}" ;;
    esac
}

TMPINI=
build_tmp() {   # merged ini -> $TMPINI (base + overrides); legacy /data/rtsp.ini honoured as base
    [ -n "$TMPINI" ] && return
    TMPINI=/tmp/camcfg.$$.ini
    if [ -f /data/rtsp.ini ]; then cp -f /data/rtsp.ini "$TMPINI"; else cp -f "$BASE" "$TMPINI"; fi
    [ -f "$OVR" ] && while IFS= read -r line; do
        case "$line" in ''|\#*) continue;; system.*) continue;; esac
        k=${line%%=*}; v=${line#*=}
        ini_set "$TMPINI" "${k%%.*}" "${k#*.}" "$v"
    done < "$OVR"
}
cleanup() { [ -n "$TMPINI" ] && rm -f "$TMPINI" "$TMPINI.tmp"; }
trap cleanup EXIT

apply() {   # $1 = restart (1/0)
    build_tmp
    cp -f "$TMPINI" "$LIVE"
    # system.* -> files read by the boot script / stream supervisor
    v=$(ovr_get system.timezone); [ -n "$v" ] && echo "$v" > "$TZF"
    v=$(ovr_get system.ntp);      [ -n "$v" ] && echo "$v" > "$NTPF"
    # keep ONVIF in sync with the main stream + login
    if [ -f "$ONVIF_BASE" ]; then
        awk -v w="$(ini_get "$LIVE" video0 width)" -v h="$(ini_get "$LIVE" video0 height)" \
            -v u="$(ini_get "$LIVE" auth user)" -v pw="$(ini_get "$LIVE" auth password)" '
            /^(user|password)=/ { next }
            /^width=/  && !wd { $0 = "width=" w;  wd = 1 }
            /^height=/ && !hd { $0 = "height=" h; hd = 1 }
            { print }
            /^port=/ && u != "" { print "user=" u; print "password=" pw }' "$ONVIF_BASE" > "$ONVIF_LIVE"
    fi
    sync
    if [ "$1" = 1 ]; then
        killall ak_rtsp_server_sample 2>/dev/null && echo "applied; stream restarting (~5-10 s)" \
            || echo "applied (stream not running; it starts at boot)"
        if pidof onvif_simple_server wsd_simple_server >/dev/null 2>&1; then
            echo "note: ONVIF picks up the change after a reboot"
        fi
    else
        echo "saved; used at the next stream restart ('camcfg apply') or reboot"
    fi
}

show() {
    build_tmp
    awk -v want="$1" -v ovrf="$OVR" '
        BEGIN { while ((getline l < ovrf) > 0) { split(l, a, "="); o[a[1]] = 1 } }
        /^[ \t]*\[/ { sec=$0; sub(/^[ \t]*\[/,"",sec); sub(/\].*$/,"",sec); if (want=="" || want==sec) print "[" sec "]"; next }
        /^[ \t]*[#;]/ || !/=/ { next }
        { if (want!="" && want!=sec) next
          k=$0; sub(/[ \t]*=.*/,"",k); gsub(/^[ \t]+/,"",k)
          v=$0; sub(/^[^=]*=[ \t]*/,"",v)
          if (k=="password") v="********"
          printf "  %s%-28s %s\n", ((sec "." k) in o) ? "*" : " ", k, v }' "$TMPINI"
    if [ -z "$1" ] || [ "$1" = system ]; then
        echo "[system]"
        printf "  %s%-28s %s\n" "$(ovr_has system.timezone && echo '*' || echo ' ')" timezone "$(eff system.timezone)"
        printf "  %s%-28s %s\n" "$(ovr_has system.ntp && echo '*' || echo ' ')" ntp "$(eff system.ntp)"
    fi
}

# expand KEY=VALUE pairs (incl. resolution) into "section.key value" lines on stdout
expand() {
    k=$(norm "${1%%=*}"); v=${1#*=}
    case "$k" in
        video[01].resolution)
            w=${v%%[xX]*}; h=${v#*[xX]}
            [ "$w" != "$v" ] || die "resolution must be WIDTHxHEIGHT, e.g. 1920x1080"
            is_int "$w" && is_int "$h" || die "resolution must be WIDTHxHEIGHT"
            [ $((w % 8)) -eq 0 ] && [ $((h % 8)) -eq 0 ] || die "width and height must be multiples of 8"
            echo "${k%.*}.width $w"; echo "${k%.*}.height $h" ;;
        *) echo "$k $v" ;;
    esac
}

CMD=$1; [ $# -gt 0 ] && shift
RESTART=1; [ "$1" = -n ] && { RESTART=0; shift; }
[ -d /data ] || die "/data not mounted"

case "$CMD" in
    show|"") show "$1" ;;
    get)
        [ -n "$1" ] || die "usage: camcfg get KEY"
        k=$(norm "$1")
        case "$k" in video[01].resolution) echo "$(eff ${k%.*}.width)x$(eff ${k%.*}.height)";;
            *) v=$(eff "$k"); [ -n "$v" ] && echo "$v" || die "$k: not set (see: camcfg keys)" ;; esac ;;
    set)
        [ $# -gt 0 ] || die "usage: camcfg set KEY=VALUE ..."
        PAIRS=/tmp/camcfg.$$.pairs; : > "$PAIRS"
        for a; do
            case "$a" in *=*) ;; *) rm -f "$PAIRS"; die "expected KEY=VALUE, got '$a'";; esac
            expand "$a" >> "$PAIRS" || { rm -f "$PAIRS"; exit 1; }
        done
        # validate everything before saving anything
        while read -r k v; do validate "$k" "$v" >/dev/null || { rm -f "$PAIRS"; exit 1; }; done < "$PAIRS"
        while read -r k v; do
            nv=$(validate "$k" "$v"); ovr_put "$k" "$nv"
            case "$k" in auth.password) echo "  $k = ********";; *) echo "  $k = $nv";; esac
        done < "$PAIRS"
        rm -f "$PAIRS"
        # cross-checks on the merged result
        build_tmp
        mw=$(ini_get "$TMPINI" video0 width); sw=$(ini_get "$TMPINI" video1 width)
        [ -n "$mw" ] && [ -n "$sw" ] && [ "$sw" -gt "$mw" ] && echo "warning: substream wider than main stream"
        [ "$(ini_get "$TMPINI" video0 code_type)" = h.265 ] && echo "note: H.265 - check your player supports it (VLC/ffmpeg/Frigate do)"
        apply $RESTART ;;
    unset)
        [ $# -gt 0 ] || die "usage: camcfg unset KEY ..."
        for a; do
            k=$(norm "$a")
            case "$k" in video[01].resolution) ovr_put ${k%.*}.width "" del; ovr_put ${k%.*}.height "" del;;
                system.timezone) ovr_put "$k" "" del; rm -f "$TZF";;
                system.ntp) ovr_put "$k" "" del; rm -f "$NTPF";;
                *) ovr_put "$k" "" del;; esac
            echo "  $k -> default"
        done
        apply $RESTART ;;
    reset) rm -f "$OVR" "$TZF" "$NTPF"; echo "all overrides removed"; apply $RESTART ;;
    export) [ -f "$OVR" ] && grep -v '^auth.password=' "$OVR"; echo "# (auth.password not exported)" ;;
    apply) apply 1 ;;
    wifi) exec /usr/sbin/wifi-set "$@" ;;
    password) exec passwd root ;;
    keys) cat <<'KEYS'
STREAMS (main.* = video0.*, sub.* = video1.*)
  main.codec        h264 | h265                      sub.codec       h264 | h265
  main.resolution   WxH, multiple of 8, max 2304x1296  sub.resolution  WxH, max 1280x720
  main.fps          1..25 (ISP tuning caps at 15)    sub.fps         1..25
  main.bitrate      256..16000 kbps                  sub.bitrate     64..4000 kbps
  main.level        10..62 (50 = level 5.0)          sub.level       10..62
LOGIN / NETWORK
  rtsp.user         letters/digits/._- ; empty = no authentication (also used by ONVIF)
  rtsp.password     4+ chars, no space ; # = \
  rtsp.port         1..65535 (default 554)
  wifi              camcfg wifi SSID PASSWORD [now]
AUDIO
  audio.code_type   aac | g711a | g711u              audio.sample_rate 8000 | 16000
RECORDING (record.*)
  mode off|continuous|motion|both     stream 0/main | 1/sub
  continuous_percent / motion_percent 0..100 (share of the card)
  continuous_max_mb / motion_max_mb   MB, >0 overrides the percent
  continuous_path / motion_path       under /mnt (e.g. /mnt/sd2/motion = 2nd SD partition)
  min_free_mb 0..100000               segment_seconds 10..3600
  motion_pre_seconds 0..15            motion_post_seconds 1..600   motion_clip_max_seconds 10..3600
  motion_sensitivity 0..100           motion_threshold 0..65535 (0 = from sensitivity)
  motion_min_cells 1..768             motion_trigger_frames 1..100  motion_debug 0|1
  motion_hook  path to a script (gets start|stop)                queue_max_kb 512..16384
SYSTEM
  system.timezone   POSIX TZ, e.g. UTC0, CET-1CEST,M3.5.0,M10.5.0/3, EST5EDT,M3.2.0,M11.1.0
  system.ntp        NTP server host (default pool.ntp.org)
KEYS
    ;;
    status)
        echo "ip:        $(ifconfig wlan0 2>/dev/null | sed -n 's/.*inet addr:\([0-9.]*\).*/\1/p')"
        wpa_cli -iwlan0 status 2>/dev/null | sed -n 's/^ssid=/wifi:      /p'
        wpa_cli -iwlan0 signal_poll 2>/dev/null | sed -n 's/^RSSI=\(.*\)/signal:    \1 dBm/p'
        echo "stream:    $(pidof ak_rtsp_server_sample >/dev/null && echo running || echo STOPPED)  ($(eff video0.code_type) $(eff video0.width)x$(eff video0.height)@$(eff video0.fps) $(eff video0.target_kbps) kbps)"
        echo "record:    mode $(eff record.mode), motion $(cut -d' ' -f1 /tmp/motion 2>/dev/null || echo -)"
        df -h /mnt/sd 2>/dev/null | tail -1 | awk '{print "sd card:   " $3 " used / " $2 " (" $5 ")"}'
        echo "time:      $(date)" ;;
    boot) apply 0 >/dev/null ;;                      # used by the boot script
    -h|--help|help) sed -n '2,23p' "$0" ;;
    *) die "unknown command '$CMD' (camcfg help)" ;;
esac
