#!/system/bin/sh
# Kodi DVB-T Live TV Setup
#
# Sets up the pipeline: RTL-SDR -> DVB-T demod -> MPEG-TS -> HTTP -> Kodi
#
# Kodi PVR connection:
#   1. Install "PVR IPTV Simple Client" addon in Kodi
#   2. Configure M3U playlist URL: http://127.0.0.1:8554/dvbt.m3u
#   3. Or add single channel: http://127.0.0.1:8554
#
# This script generates the M3U playlist from configured channels
# and starts the DVB-T HTTP stream server.

MODDIR="/data/adb/modules/driver-manager"
CONFDIR="$MODDIR/config"
STREAMDIR="$MODDIR/streams"
LOGFILE="$MODDIR/driver-manager.log"
KODI_PORT=$(cat "$CONFDIR/kodi_stream_port" 2>/dev/null || echo "8554")
CHANNELS_FILE="$CONFDIR/dvbt_channels.conf"

mkdir -p "$STREAMDIR"

mlog() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [kodi] $1" >> "$LOGFILE"
}

# Generate M3U playlist from channel config
# Format of dvbt_channels.conf:
#   # Channel Name | Frequency (Hz) | Bandwidth | TX Mode | Constellation | Code Rate | Guard
#   BBC One|506000000|8|8k|64qam|2/3|1/32
#   ITV|514000000|8|8k|64qam|2/3|1/32
generate_m3u() {
    M3U="$STREAMDIR/dvbt.m3u"
    echo '#EXTM3U' > "$M3U"

    if [ ! -f "$CHANNELS_FILE" ]; then
        # Create default channel config
        cat > "$CHANNELS_FILE" << 'CHANNELS'
# DVB-T Channel List
# Format: Name|Frequency(Hz)|Bandwidth(MHz)|TxMode|Constellation|CodeRate|Guard
# Edit this file to add your local channels
# Find channels with: rtl_mode_switch.sh spectrum (then check results)
#
# Example channels (UK Freeview):
Channel 1|506000000|8|8k|64qam|2/3|1/32
Channel 2|514000000|8|8k|64qam|2/3|1/32
Channel 3|522000000|8|8k|64qam|2/3|1/32
CHANNELS
        mlog "Created default channel config at $CHANNELS_FILE"
    fi

    CH_NUM=1
    while IFS='|' read -r NAME FREQ BW TXMODE CONST CR GUARD; do
        # Skip comments and empty lines
        case "$NAME" in
            \#*|"") continue ;;
        esac

        # Each channel gets its own stream port
        CH_PORT=$((KODI_PORT + CH_NUM))
        echo "#EXTINF:-1,$NAME" >> "$M3U"
        echo "http://127.0.0.1:$CH_PORT" >> "$M3U"
        CH_NUM=$((CH_NUM + 1))
    done < "$CHANNELS_FILE"

    mlog "Generated M3U playlist: $M3U ($((CH_NUM - 1)) channels)"
}

# Start a stream server for a specific channel
# Called when Kodi connects to a channel URL
start_channel_stream() {
    CH_PORT=$1
    FREQ=$2
    BW=$3
    TXMODE=$4
    CONST=$5
    CR=$6
    GUARD=$7
    CH_NAME=$8

    TERMUX="/data/data/com.termux/files/usr/bin"
    SDR_TV="$MODDIR/scripts/sdr_tv.py"

    FIFO="$STREAMDIR/ch_${CH_PORT}.ts"
    rm -f "$FIFO"
    mkfifo "$FIFO" 2>/dev/null

    if [ -x "$TERMUX/python3" ] && [ -f "$SDR_TV" ]; then
        # Start DVB-T demodulator
        "$TERMUX/python3" "$SDR_TV" dvbt \
            --freq "$FREQ" \
            --bandwidth "$BW" \
            --transmission-mode "$TXMODE" \
            --constellation "$CONST" \
            --code-rate "$CR" \
            --guard-interval "$GUARD" \
            > "$FIFO" 2>>"$LOGFILE" &
        DVB_PID=$!

        # HTTP stream server for this channel
        (while true; do
            (echo -e "HTTP/1.1 200 OK\r\nContent-Type: video/mp2t\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r"; cat "$FIFO") | \
                nc -l -p "$CH_PORT" 2>/dev/null
            # If Kodi disconnects, kill the demodulator
            kill "$DVB_PID" 2>/dev/null
            break
        done) &

        mlog "Channel stream started: $CH_NAME on port $CH_PORT (freq=$FREQ)"
    else
        mlog "ERROR: python3 or sdr_tv.py not found for channel stream"
    fi
}

# Serve M3U playlist on the base port
serve_m3u() {
    M3U="$STREAMDIR/dvbt.m3u"
    (while true; do
        M3U_CONTENT=$(cat "$M3U" 2>/dev/null)
        RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: audio/x-mpegurl\r\nContent-Length: ${#M3U_CONTENT}\r\nConnection: close\r\n\r\n${M3U_CONTENT}"
        echo -e "$RESPONSE" | nc -l -p "$KODI_PORT" 2>/dev/null
    done) &
    mlog "M3U server on port $KODI_PORT"
}

case "$1" in
    setup)
        generate_m3u
        serve_m3u
        mlog "Kodi DVB-T setup complete"
        mlog "Add to Kodi PVR IPTV Simple Client:"
        mlog "  M3U URL: http://127.0.0.1:$KODI_PORT/dvbt.m3u"
        echo "Kodi setup complete."
        echo "In Kodi: Settings > PVR & Live TV > PVR IPTV Simple Client"
        echo "M3U URL: http://127.0.0.1:$KODI_PORT/dvbt.m3u"
        ;;
    scan)
        # Scan for DVB-T channels using spectrum analysis
        echo "Scanning for DVB-T channels..."
        echo "Common DVB-T frequency ranges:"
        echo "  VHF Band III: 174-230 MHz"
        echo "  UHF Band IV:  470-582 MHz"
        echo "  UHF Band V:   582-862 MHz"
        echo ""
        echo "Starting spectrum scan on UHF band..."
        "$MODDIR/scripts/rtl_mode_switch.sh" spectrum
        echo "Check $MODDIR/streams/spectrum_data.csv for results"
        ;;
    channels)
        # List configured channels
        if [ -f "$CHANNELS_FILE" ]; then
            echo "Configured DVB-T channels:"
            grep -v "^#" "$CHANNELS_FILE" | grep -v "^$" | while IFS='|' read -r NAME FREQ BW TXMODE CONST CR GUARD; do
                FREQ_MHZ=$(echo "scale=1; $FREQ / 1000000" | bc 2>/dev/null || echo "$FREQ")
                echo "  $NAME — ${FREQ_MHZ} MHz (${BW}MHz BW, $TXMODE, $CONST, $CR, $GUARD)"
            done
        else
            echo "No channels configured. Edit: $CHANNELS_FILE"
        fi
        ;;
    *)
        echo "Usage: kodi_dvbt_setup.sh {setup|scan|channels}"
        echo ""
        echo "  setup    - Generate M3U and start stream servers"
        echo "  scan     - Scan spectrum for DVB-T channels"
        echo "  channels - List configured channels"
        ;;
esac
