#!/usr/bin/env bash
set -euo pipefail

usage() {
    printf '%s\n' 'Usage: roku-tv {status|kodi|standby}' \
        '  status   Read TV power and the reported HDMI-CEC source' \
        '  kodi     Wake the TV and select Bounsweet (Kodi)' \
        '  standby  Send standby to the TV'
}

if [[ $# != 1 ]]; then
    usage >&2
    exit 2
fi
case "$1" in
    -h|--help) usage; exit 0 ;;
    status|kodi|standby) ;;
    *) usage >&2; exit 2 ;;
esac

timeout 20 ssh -T -o BatchMode=yes -o ConnectTimeout=5 bounsweet sh -s -- "$1" <<'REMOTE'
set -eu
cec() {
    cec-ctl -d /dev/cec0 "$@"
}

address=$(cec | awk '/Physical Address[[:space:]]*:/ {print $NF; exit}')
case "$address" in
    [1-9a-e].[0-9a-f].[0-9a-f].[0-9a-f]) ;;
    *) echo 'Bounsweet has no usable HDMI-CEC address' >&2; exit 1 ;;
esac

status() {
    power_reply=$(cec --to 0 --give-device-power-status)
    source_reply=$(cec --request-active-source)
    power=$(printf '%s\n' "$power_reply" | awk -F': ' '/pwr-state:/ {sub(/ \(.*$/, "", $2); print $2; exit}')
    source=$(printf '%s\n' "$source_reply" | awk '/phys-addr:/ {print $NF; exit}')
    printf 'tv_power=%s\nactive_source=%s\nkodi_source=%s\n' "${power:-unknown}" "${source:-unknown}" "$address"
}

roku_reports_kodi() {
    case "$address" in
        [1-4].0.0.0) input="tvinput.hdmi${address%%.*}" ;;
        *) return 1 ;;
    esac
    active_app=$(curl -fsS --max-time 4 http://10.56.5.46:8060/query/active-app 2>/dev/null) || return 1
    printf '%s\n' "$active_app" | grep -Fq "<app id=\"$input\""
}

send() {
    reply=$(cec "$@")
    if printf '%s\n' "$reply" | grep -qi 'Tx, Not OK'; then
        printf '%s\n' 'HDMI-CEC transmit failed.' >&2
        exit 1
    fi
}

case "$1" in
    status)
        status
        ;;
    kodi)
        send --to 0 --image-view-on
        sleep 1
        send --active-source "phys-addr=$address"
        printf 'requested_source=%s\n' "$address"
        sleep 1
        status
        if [ "${source:-unknown}" = "$address" ]; then
            printf '%s\n' 'source_verified_by=cec'
        elif roku_reports_kodi; then
            printf '%s\n' 'source_verified_by=roku_active_app'
        else
            echo 'Kodi source selection could not be confirmed.' >&2
            exit 1
        fi
        ;;
    standby)
        send --to 0 --standby
        printf '%s\n' 'requested_power=standby'
        status
        ;;
esac
REMOTE
