#!/bin/bash
# setup.sh
# One-time server setup for the ABCC Roku live stream stack.
# Run as a user with sudo access on Oracle Cloud Ubuntu.
#
# Usage: sudo bash scripts/setup.sh

set -e

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
BASE_DIR="$(dirname "$SCRIPT_DIR")"

echo "=== ABCC Server Setup ==="

# -----------------------------------------------------------------------
# 1. Firewall — open RTMP port 1935
#    Oracle Cloud uses iptables (not ufw). Rules are persisted to
#    /etc/iptables/rules.v4 and restored at boot by iptables-persistent.
# -----------------------------------------------------------------------
echo "[1/5] Configuring firewall (iptables)..."

# Only add the rule if it isn't already there
if ! iptables -C INPUT -p tcp -m state --state NEW --dport 1935 -j ACCEPT 2>/dev/null; then
    # Insert before the final REJECT rule
    REJECT_LINE=$(iptables -L INPUT --line-numbers -n | awk '/REJECT/ {print $1; exit}')
    iptables -I INPUT "${REJECT_LINE}" -p tcp -m state --state NEW --dport 1935 -j ACCEPT
    echo "  Port 1935 (RTMP) opened."
else
    echo "  Port 1935 already open, skipping."
fi

# Persist rules
mkdir -p /etc/iptables
iptables-save > /etc/iptables/rules.v4

# Ensure rules are restored on reboot
if ! dpkg -l | grep -q iptables-persistent; then
    echo "  Installing iptables-persistent..."
    DEBIAN_FRONTEND=noninteractive apt-get install -y iptables-persistent
fi

echo "  NOTE: You must also open port 1935 in the Oracle Cloud VCN Security List"
echo "        (OCI Console → Networking → VCN → Security Lists → Ingress Rules)."

# -----------------------------------------------------------------------
# 2. Live HLS output directory
# -----------------------------------------------------------------------
echo "[2/5] Setting up live HLS directory..."

LIVE_DIR="$BASE_DIR/live"
mkdir -p "$LIVE_DIR"
chown -R www-data:www-data "$LIVE_DIR"
chmod 755 "$LIVE_DIR"

# Write .htaccess if it doesn't exist
if [ ! -f "$LIVE_DIR/.htaccess" ]; then
    cat > "$LIVE_DIR/.htaccess" << 'HTACCESS'
# HLS MIME types
AddType application/vnd.apple.mpegurl .m3u8
AddType video/mp2t .ts

# No caching for live playlist — must always be fresh
<FilesMatch "\.m3u8$">
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires "0"
</FilesMatch>

# Short cache for segments — they don't change once written
<FilesMatch "\.ts$">
    Header set Cache-Control "max-age=60"
</FilesMatch>

# CORS — allow Roku devices to fetch the stream
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, OPTIONS"
Header set Access-Control-Allow-Headers "Origin, Range"
Header set Access-Control-Expose-Headers "Content-Length, Content-Range"
HTACCESS
    echo "  .htaccess written."
fi

# -----------------------------------------------------------------------
# 3. Apache — enable required modules
# -----------------------------------------------------------------------
echo "[3/5] Enabling Apache modules..."
a2enmod headers expires mime > /dev/null 2>&1
systemctl reload apache2
echo "  Apache reloaded."

# -----------------------------------------------------------------------
# 4. Systemd service for live stream
# -----------------------------------------------------------------------
echo "[4/5] Setting www-data write permissions..."

# Apache/PHP runs as www-data; files created by ubuntu (cron/manual) are
# not writable by www-data unless we set group ownership + write bit.

# Directories that www-data must be able to create files in
chgrp www-data "$BASE_DIR/data" "$BASE_DIR/logs"
chmod g+w      "$BASE_DIR/data" "$BASE_DIR/logs"

# Individual files www-data must be able to write
for f in \
    "$BASE_DIR/data/cookies.txt" \
    "$BASE_DIR/data/schedule.json" \
    "$BASE_DIR/data/packages.json" \
    "$BASE_DIR/logs/stream.log" \
    "$BASE_DIR/logs/error.log"
do
    [ -f "$f" ] && chgrp www-data "$f" && chmod g+w "$f"
done
echo "  Done."

# -----------------------------------------------------------------------
# 5. Systemd service for live stream
# -----------------------------------------------------------------------
echo "[5/5] Installing abcc-live systemd service..."

cat > /etc/systemd/system/abcc-live.service << 'SERVICE'
[Unit]
Description=ABCC Live Stream (RTMP to HLS via FFmpeg)
After=network.target

[Service]
Type=simple
User=www-data
ExecStart=$BASE_DIR/scripts/start_live_stream.sh
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
SERVICE

systemctl daemon-reload
systemctl enable abcc-live.service
echo "  abcc-live service enabled (not started — start when you go live)."

echo ""
echo "=== Setup complete ==="
echo ""
echo "To start streaming:"
echo "  sudo systemctl start abcc-live"
echo "  sudo journalctl -u abcc-live -f"
echo ""
echo "OBS settings:"
echo "  Server:     rtmp://$(curl -s ifconfig.me 2>/dev/null || echo '<server-ip>'):1935/live"
echo "  Stream Key: stream"
echo ""
echo "Roku will fetch: https://media.abcc.org/live/stream.m3u8"


pip install pillow arabic-reshaper python-bidi