#!/bin/bash
# ==========================================================
# 🔴 AUTO STREAM INSTALLER V2 (with Auto Key Updater)
# Author: ANIL | Setup Script by ChatGPT
# ==========================================================

set -e
echo "🚀 Installing Auto Stream System..."
sleep 2

apt update -y
apt install -y nginx libnginx-mod-rtmp ffmpeg
mkdir -p /root/videos
touch /root/keys.txt

cat > /root/keys.txt <<'KEYS'
abcd-xxxx-yyyy-zzzz-1111
KEYS

cat > /root/auto_stream.sh <<'SCRIPT'
#!/bin/bash
VIDEO_DIR="/root/videos"
LOG="/root/auto_stream.log"
FFMPEG="/usr/bin/ffmpeg"
sleep 15
echo "===== Auto Stream Starting $(date) =====" >> "$LOG"
while true; do
    for FILE in "$VIDEO_DIR"/*; do
        if [ -f "$FILE" ]; then
            echo "Now streaming: $FILE at $(date)" >> "$LOG"
            "$FFMPEG" -re -i "$FILE" \
-c:v libx264 -preset veryfast -b:v 6000k -maxrate 6000k -bufsize 12000k \
-pix_fmt yuv420p -g 50 -c:a aac -b:a 192k -ar 44100 \
-f flv rtmp://localhost/live/stream >> "$LOG" 2>&1
        fi
    done
done
SCRIPT

cat > /root/update_keys.sh <<'SCRIPT'
#!/bin/bash
NGINX_CONF="/etc/nginx/nginx.conf"
KEYS_FILE="/root/keys.txt"
cp "$NGINX_CONF" "$NGINX_CONF.backup_$(date +%F_%H-%M-%S)"
cat > "$NGINX_CONF" <<'CONFIG'
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;
include /etc/nginx/modules-enabled/*.conf;
events { worker_connections 768; }
http { include /etc/nginx/mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; }
rtmp {
    server {
        listen 1935;
        chunk_size 4096;
        application live {
            live on;
            record off;
CONFIG
while IFS= read -r key
do
    if [[ ! -z "$key" ]]; then
        echo "            push rtmp://a.rtmp.youtube.com/live2/$key;" >> "$NGINX_CONF"
    fi
done < "$KEYS_FILE"
cat >> "$NGINX_CONF" <<'CONFIG'
        }
    }
}
CONFIG
nginx -t && systemctl restart nginx
if [ $? -eq 0 ]; then
    echo "✅ Keys updated successfully & Nginx restarted."
else
    echo "❌ Error in Nginx configuration. Please check manually."
fi
SCRIPT

cat > /root/auto_key_updater.sh <<'SCRIPT'
#!/bin/bash
KEYS_FILE="/root/keys.txt"
LAST_HASH=""
echo "🕒 Auto Key Updater Started — $(date)"
while true; do
    if [ -f "$KEYS_FILE" ]; then
        NEW_HASH=$(md5sum "$KEYS_FILE" | awk '{print $1}')
        if [ "$NEW_HASH" != "$LAST_HASH" ]; then
            echo "🔄 Keys file changed at $(date). Updating Nginx..."
            bash /root/update_keys.sh
            LAST_HASH="$NEW_HASH"
        fi
    else
        echo "⚠️ Keys file not found: $KEYS_FILE"
    fi
    sleep 60
done
SCRIPT

chmod +x /root/auto_stream.sh /root/update_keys.sh /root/auto_key_updater.sh
/root/update_keys.sh

cat > /etc/systemd/system/auto_stream.service <<'SERVICE'
[Unit]
Description=Auto Stream to YouTube
After=network.target
[Service]
ExecStart=/root/auto_stream.sh
Restart=always
User=root
[Install]
WantedBy=multi-user.target
SERVICE

cat > /etc/systemd/system/auto_key_updater.service <<'SERVICE'
[Unit]
Description=Auto Key Updater
After=network.target
[Service]
ExecStart=/root/auto_key_updater.sh
Restart=always
User=root
[Install]
WantedBy=multi-user.target
SERVICE

systemctl daemon-reload
systemctl enable auto_stream.service auto_key_updater.service
systemctl start auto_stream.service auto_key_updater.service

echo "✅ Installation Complete!"
echo "📁 Put videos in /root/videos/"
echo "🗝️ Edit keys in /root/keys.txt"
echo "🔁 Auto Key Updater checks every 1 minute"
echo "▶️ Stream auto-starts on reboot!"
