#!/usr/bin/env bash
set -euo pipefail
DOMAIN="${1:-}"; UPSTREAM="${2:-}"
apt-get update -y && apt-get install -y nginx
cat >/etc/nginx/sites-available/hls-proxy.conf <<EOF
server { listen 80; server_name ${DOMAIN:-_};
  add_header Access-Control-Allow-Origin * always;
  add_header Access-Control-Allow-Headers * always;
  add_header Access-Control-Allow-Methods GET,HEAD,OPTIONS always;
  location ~* \.m3u8$ { proxy_pass http://${UPSTREAM}\$request_uri; proxy_set_header Host ${UPSTREAM}; proxy_set_header Referer http://${UPSTREAM}/; proxy_set_header Origin http://${UPSTREAM}; proxy_set_header Range \$http_range; proxy_buffering off; }
  location ~* \.(ts|mp4)$ { proxy_pass http://${UPSTREAM}\$request_uri; proxy_set_header Host ${UPSTREAM}; proxy_set_header Referer http://${UPSTREAM}/; proxy_set_header Origin http://${UPSTREAM}; proxy_set_header Range \$http_range; proxy_buffering off; }
  location / { return 200 "ok\n"; add_header Content-Type text/plain; } }
EOF
ln -sf /etc/nginx/sites-available/hls-proxy.conf /etc/nginx/sites-enabled/hls-proxy.conf
rm -f /etc/nginx/sites-enabled/default
systemctl restart nginx
echo "Done"
