#!/bin/bash

######################################################################
# Der Netzwerkstatus wird nach dem Booten überprüft
# Wenn Letzterer i.O., dann HTTP-Status abfragen
#
# wenn 304, dann 304.sh triggern
# wenn 200 und JSON valide, parse.sh triggern
# in jedem andern Fall Netzwerk mittels nwck.sh prüfen 
######################################################################


DOMAIN="$( /home/snowtv/bin/getdomain.sh | tr -d "[']")"
NWSTATE="$(</home/snowtv/bin/nwstate)"
NINC="$(( NWSTATE + 1 ))"
TOK="$(</home/snowtv/bin/token)"
ID="$( /home/snowtv/bin/getid.sh)"
echo "$ID"

httpstat () {
    local URL="${DOMAIN}/apg-mp?device=${ID}"
    if [ -f /home/snowtv/bin/cfg_pending ]; then
        # cfg_pending gesetzt: ohne If-Modified-Since, &update=cfg → Server sendet cfgCore erneut
        curl -k --connect-timeout 5 --max-time 10 -o /home/snowtv/Downloads/tmp.json -s -w "%{http_code}\\n" \
            -H "APG-Authorization: ${TOK}" "${URL}&update=cfg" --user-agent "apg-mp"
    else
        curl -k --connect-timeout 5 --max-time 10 -z /home/snowtv/Downloads/tmp.json -o /home/snowtv/Downloads/tmp.json -s -w "%{http_code}\\n" \
            -H "APG-Authorization: ${TOK}" "$URL" --user-agent "apg-mp"
    fi
}
echo $(httpstat) | tee /home/snowtv/bin/httpstat.txt
HTTPSTAT="$(</home/snowtv/bin/httpstat.txt)"

CK="$( /home/snowtv/bin/validate.sh)"


# nwstate initialisieren falls Datei leer oder fehlend (z.B. nach erstem Boot)
if [ -z "$NWSTATE" ]; then
	echo "0" | tee /home/snowtv/bin/nwstate

# Fehlerschwelle erreicht: Fehlerbehandlung + Netzwerkcheck
elif [ "$NWSTATE" -ge "4" ]; then
	/home/snowtv/bin/err.sh
	/home/snowtv/bin/nwck.sh

# Normalbetrieb, Playout regeln mit 304.sh
elif [ "$HTTPSTAT" == "304" ]; then
	/home/snowtv/bin/304.sh
	/home/snowtv/bin/shot.sh
	sleep 1
	/home/snowtv/bin/imgupl.sh
	echo "0" | tee /home/snowtv/bin/nwstate

# Mediaplayer muss neu konfiguriert werden
elif [ "$HTTPSTAT" == "200" ] && [ "$CK" == "0" ]; then
	/home/snowtv/bin/parse.sh
	echo "0" | tee /home/snowtv/bin/nwstate

# HTTP 200 aber JSON ungültig: cfg_pending setzen → nächster Poll erzwingt erneuten Download
elif [ "$HTTPSTAT" == "200" ]; then
	echo "$(date)  WARN: HTTP-Status '200' aber JSON ungültig (CK=$CK) – cfg_pending gesetzt, nwstate=$NINC" | tee -a /var/log/stv.log
	touch /home/snowtv/bin/cfg_pending
	echo "$NINC" > /home/snowtv/bin/nwstate

# Unerwarteter HTTP-Status: Zähler erhöhen, loggen
else
	echo "$(date)  WARN: HTTP-Status '$HTTPSTAT' – nwstate=$NINC" | tee -a /var/log/stv.log
	echo "$NINC" > /home/snowtv/bin/nwstate

fi

exit 0
