#!/usr/bin/env bash
# Install the Besorah channel on a Roku in developer mode.
#
#   ./besorah-roku-install.sh <roku-ip> <dev-password> [besorah-roku-X.Y.Z.zip]
#
# One-time TV setup (enable developer mode, choose the password) is on the
# Besorah Roku page. Installing launches the channel on the TV straight away,
# and it replaces any other sideloaded ("dev") channel: a Roku holds only one.
set -euo pipefail
IP="${1:-}"; PASS="${2:-}"; ZIP="${3:-}"
[ -n "$IP" ] && [ -n "$PASS" ] || { echo "usage: $0 <roku-ip> <dev-password> [channel.zip]" >&2; exit 2; }
if [ -z "$ZIP" ]; then
  ZIP="$(ls "$(dirname "$0")"/besorah-roku-*.zip 2>/dev/null | tail -1 || true)"
fi
[ -f "$ZIP" ] || { echo "Can't find the channel zip; pass it as the third argument." >&2; exit 2; }
nc -z -G 3 "$IP" 80 >/dev/null 2>&1 || { echo "Nothing answers at $IP:80. Is the Roku on, and is developer mode enabled?" >&2; exit 1; }
echo "Installing $(basename "$ZIP") on $IP ..."
OUT="$(curl -s -m 120 --digest -u "rokudev:$PASS" -F mysubmit=Install -F "archive=@$ZIP" "http://$IP/plugin_install" \
  | grep -oE 'Install Success|Identical to previous|Install Failure|Unauthorized' | head -1 || true)"
case "$OUT" in
  "Install Success"|"Identical to previous") echo "$OUT. Besorah is opening on your TV." ;;
  *) echo "Install failed (${OUT:-no response}). Check the developer password." >&2; exit 1 ;;
esac
