#!/bin/bash
# ============================================================
# AdCast Digital Signage Player - Raspberry Pi Installer
# Supports: Raspberry Pi 3, 4, 5 (Raspberry Pi OS Lite or Desktop)
# ============================================================

set -e

ADCAST_DIR="/opt/adcast"
ADCAST_USER="adcast"
DEFAULT_SERVER="https://ads.anettv.org"

echo ""
echo "  ╔══════════════════════════════════════╗"
echo "  ║   AdCast Player - Raspberry Pi       ║"
echo "  ║   Digital Signage Installer          ║"
echo "  ╚══════════════════════════════════════╝"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "Please run as root: sudo bash install.sh"
    exit 1
fi

# Get server URL
read -p "Enter your AdCast server URL [$DEFAULT_SERVER]: " SERVER_URL
SERVER_URL=${SERVER_URL:-$DEFAULT_SERVER}

# Validate URL
if [[ ! "$SERVER_URL" =~ ^https?:// ]]; then
    echo "Error: URL must start with http:// or https://"
    exit 1
fi

echo ""
echo "Installing AdCast Player..."
echo "Server: $SERVER_URL"
echo ""

# 1. Update system
echo "[1/7] Updating system packages..."
apt-get update -qq
apt-get upgrade -y -qq

# 2. Install dependencies
echo "[2/7] Installing dependencies..."
apt-get install -y -qq \
    chromium-browser \
    unclutter \
    xdotool \
    xserver-xorg \
    x11-xserver-utils \
    xinit \
    openbox \
    jq \
    curl \
    fonts-noto \
    2>/dev/null

# 3. Create adcast user if not exists
echo "[3/7] Setting up user..."
if ! id "$ADCAST_USER" &>/dev/null; then
    useradd -m -s /bin/bash "$ADCAST_USER"
    usermod -aG video,audio,input,tty "$ADCAST_USER"
fi

# 4. Create directory structure
echo "[4/7] Creating player files..."
mkdir -p "$ADCAST_DIR"
mkdir -p "$ADCAST_DIR/cache"
mkdir -p "$ADCAST_DIR/logs"

# Generate device UUID
DEVICE_UUID="ADCAST-PI-$(cat /proc/cpuinfo | grep Serial | cut -d ' ' -f 2 | tail -c 9 | tr '[:lower:]' '[:upper:]')"
if [ ${#DEVICE_UUID} -lt 14 ]; then
    DEVICE_UUID="ADCAST-PI-$(hostname | md5sum | head -c 8 | tr '[:lower:]' '[:upper:]')"
fi

# Save config
cat > "$ADCAST_DIR/config.json" << CONF
{
    "server_url": "$SERVER_URL",
    "device_uuid": "$DEVICE_UUID",
    "heartbeat_interval": 60,
    "screen_rotation": 0,
    "kiosk_mode": true,
    "auto_update": true,
    "log_level": "info"
}
CONF

# 5. Create the player launch script
cat > "$ADCAST_DIR/start.sh" << 'PLAYER'
#!/bin/bash
# AdCast Pi Player - Launcher
ADCAST_DIR="/opt/adcast"
CONFIG="$ADCAST_DIR/config.json"
LOG="$ADCAST_DIR/logs/player.log"

SERVER_URL=$(jq -r '.server_url' "$CONFIG")
DEVICE_UUID=$(jq -r '.device_uuid' "$CONFIG")
ROTATION=$(jq -r '.screen_rotation // 0' "$CONFIG")

echo "$(date) - Starting AdCast Player" >> "$LOG"
echo "  Server: $SERVER_URL" >> "$LOG"
echo "  UUID: $DEVICE_UUID" >> "$LOG"

# Set screen rotation
if [ "$ROTATION" != "0" ]; then
    xrandr --output HDMI-1 --rotate "$ROTATION" 2>/dev/null || true
    xrandr --output HDMI-2 --rotate "$ROTATION" 2>/dev/null || true
fi

# Disable screen saver and power management
xset s off
xset -dpms
xset s noblank

# Hide mouse cursor after 3 seconds of inactivity
unclutter -idle 3 -root &

# Register device with server
echo "$(date) - Registering device..." >> "$LOG"
REGISTER_RESPONSE=$(curl -s -X POST "$SERVER_URL/api/device/register" \
    -H "Content-Type: application/json" \
    -d "{\"uuid\": \"$DEVICE_UUID\", \"model\": \"Raspberry Pi\", \"os_version\": \"$(cat /etc/os-release | grep VERSION_ID | cut -d= -f2 | tr -d '\"')\"}" 2>/dev/null)

PAIRING_CODE=$(echo "$REGISTER_RESPONSE" | jq -r '.pairing_code // empty')
DEVICE_ID=$(echo "$REGISTER_RESPONSE" | jq -r '.device_id // empty')

if [ -n "$PAIRING_CODE" ]; then
    echo "$(date) - Pairing code: $PAIRING_CODE" >> "$LOG"
fi

# Player URL — the web player with device context
PLAYER_URL="$SERVER_URL/api/device/web-player?uuid=$DEVICE_UUID"

# Start heartbeat in background
(
    while true; do
        INTERVAL=$(jq -r '.heartbeat_interval // 60' "$CONFIG")

        # Get system info
        STORAGE_TOTAL=$(df / --output=size -BM | tail -1 | tr -d ' M')
        STORAGE_USED=$(df / --output=used -BM | tail -1 | tr -d ' M')
        STORAGE_FREE=$(df / --output=avail -BM | tail -1 | tr -d ' M')
        RAM_TOTAL=$(($(grep MemTotal /proc/meminfo | awk '{print $2}') / 1024))
        RAM_FREE=$(($(grep MemAvailable /proc/meminfo | awk '{print $2}') / 1024))
        WIFI_SIGNAL=$(iwconfig 2>/dev/null | grep "Signal level" | awk -F'=' '{print $3}' | awk '{print $1}' | tr -d '-' | head -1)
        IP_ADDR=$(hostname -I | awk '{print $1}')
        UPTIME_SEC=$(cat /proc/uptime | awk '{print int($1)}')
        CPU_TEMP=$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null | awk '{printf "%.1f", $1/1000}')

        curl -s -X POST "$SERVER_URL/api/device/heartbeat" \
            -H "Content-Type: application/json" \
            -d "{
                \"uuid\": \"$DEVICE_UUID\",
                \"ip_address\": \"$IP_ADDR\",
                \"storage_total_mb\": $STORAGE_TOTAL,
                \"storage_used_mb\": $STORAGE_USED,
                \"storage_free_mb\": $STORAGE_FREE,
                \"ram_total_mb\": $RAM_TOTAL,
                \"ram_free_mb\": $RAM_FREE,
                \"wifi_signal\": ${WIFI_SIGNAL:-0},
                \"current_content\": \"web-player\",
                \"app_version\": \"pi-1.0.0\",
                \"version_code\": 1,
                \"screen_on\": true,
                \"volume\": 50,
                \"is_locked\": false,
                \"uptime_seconds\": $UPTIME_SEC
            }" >> "$LOG" 2>&1

        echo "" >> "$LOG"
        sleep "$INTERVAL"
    done
) &

# Launch Chromium in kiosk mode
echo "$(date) - Launching browser..." >> "$LOG"

# Wait for X to be ready
sleep 2

# Show pairing screen first if not paired
if [ -z "$DEVICE_ID" ] || [ "$DEVICE_ID" = "null" ]; then
    # Show pairing info screen
    chromium-browser \
        --kiosk \
        --no-first-run \
        --disable-infobars \
        --disable-session-crashed-bubble \
        --disable-translate \
        --noerrdialogs \
        --disable-features=TranslateUI \
        --check-for-update-interval=31536000 \
        --autoplay-policy=no-user-gesture-required \
        --disable-component-update \
        --disable-background-networking \
        --disable-sync \
        --incognito \
        "data:text/html,<html><head><style>*{margin:0;padding:0;box-sizing:border-box}body{background:%230f172a;color:white;font-family:system-ui;display:flex;align-items:center;justify-content:center;min-height:100vh}.box{text-align:center;max-width:500px}h1{font-size:48px;color:%23818cf8;margin-bottom:16px}p{color:%2394a3b8;font-size:18px;margin:8px 0}.code{font-size:72px;font-weight:700;letter-spacing:8px;color:white;margin:32px 0;font-family:monospace}.uuid{font-size:12px;color:%23475569;margin-top:24px}</style></head><body><div class='box'><h1>AdCast Player</h1><p>Pair this device in your AdCast panel</p><div class='code'>${PAIRING_CODE:-------}</div><p>Enter this code at $SERVER_URL</p><div class='uuid'>Device: $DEVICE_UUID</div></div></body></html>" &

    # Wait for pairing (check every 10 seconds)
    echo "$(date) - Waiting for pairing..." >> "$LOG"
    while true; do
        RESPONSE=$(curl -s -X POST "$SERVER_URL/api/device/heartbeat" \
            -H "Content-Type: application/json" \
            -d "{\"uuid\": \"$DEVICE_UUID\", \"ip_address\": \"$(hostname -I | awk '{print $1}')\", \"storage_total_mb\": 1000, \"storage_used_mb\": 500, \"storage_free_mb\": 500, \"app_version\": \"pi-1.0.0\", \"version_code\": 1, \"screen_on\": true, \"volume\": 50, \"is_locked\": false, \"uptime_seconds\": 0}" 2>/dev/null)

        HAS_PLAYLIST=$(echo "$RESPONSE" | jq -r '.has_update // false')
        STATUS=$(echo "$RESPONSE" | jq -r '.status // empty')

        if [ "$STATUS" = "ok" ]; then
            echo "$(date) - Device paired!" >> "$LOG"
            # Kill pairing screen
            pkill -f chromium-browser 2>/dev/null
            sleep 2
            break
        fi
        sleep 10
    done
fi

# Main player loop — restart browser if it crashes
while true; do
    chromium-browser \
        --kiosk \
        --no-first-run \
        --disable-infobars \
        --disable-session-crashed-bubble \
        --disable-translate \
        --noerrdialogs \
        --disable-features=TranslateUI \
        --check-for-update-interval=31536000 \
        --autoplay-policy=no-user-gesture-required \
        --disable-component-update \
        --disable-background-networking \
        --disable-sync \
        --enable-features=OverlayScrollbar \
        --disable-gpu-compositing \
        --incognito \
        --start-fullscreen \
        "$PLAYER_URL" 2>> "$LOG"

    echo "$(date) - Browser exited, restarting in 5s..." >> "$LOG"
    sleep 5
done
PLAYER

chmod +x "$ADCAST_DIR/start.sh"

# 6. Create systemd service for autostart
echo "[5/7] Setting up autostart..."

cat > /etc/systemd/system/adcast-player.service << SERVICE
[Unit]
Description=AdCast Digital Signage Player
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$ADCAST_USER
Environment=DISPLAY=:0
Environment=XAUTHORITY=/home/$ADCAST_USER/.Xauthority
ExecStartPre=/bin/sleep 5
ExecStart=/opt/adcast/start.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
SERVICE

# Create X autostart via .xinitrc
cat > /home/$ADCAST_USER/.xinitrc << 'XINIT'
#!/bin/bash
exec openbox-session &
/opt/adcast/start.sh
XINIT
chmod +x /home/$ADCAST_USER/.xinitrc
chown $ADCAST_USER:$ADCAST_USER /home/$ADCAST_USER/.xinitrc

# Auto-login and start X
mkdir -p /etc/systemd/system/getty@tty1.service.d/
cat > /etc/systemd/system/getty@tty1.service.d/override.conf << AUTOLOGIN
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin $ADCAST_USER --noclear %I \$TERM
AUTOLOGIN

# Start X on login
echo '[ -z "$DISPLAY" ] && [ "$(tty)" = "/dev/tty1" ] && startx' >> /home/$ADCAST_USER/.bash_profile
chown $ADCAST_USER:$ADCAST_USER /home/$ADCAST_USER/.bash_profile

# 7. Set permissions
echo "[6/7] Setting permissions..."
chown -R $ADCAST_USER:$ADCAST_USER "$ADCAST_DIR"

# Enable service
systemctl daemon-reload
systemctl enable adcast-player.service

echo ""
echo "[7/7] Done!"
echo ""
echo "  ╔══════════════════════════════════════╗"
echo "  ║   Installation Complete!             ║"
echo "  ╠══════════════════════════════════════╣"
echo "  ║                                      ║"
echo "  ║   Device UUID: $DEVICE_UUID    ║"
echo "  ║   Server: $SERVER_URL    ║"
echo "  ║   Config: $ADCAST_DIR/config.json    ║"
echo "  ║                                      ║"
echo "  ║   The player will start on reboot.   ║"
echo "  ║   Reboot now? (y/n)                  ║"
echo "  ╚══════════════════════════════════════╝"
echo ""

read -p "Reboot now? [y/N]: " REBOOT
if [[ "$REBOOT" =~ ^[Yy]$ ]]; then
    echo "Rebooting..."
    reboot
else
    echo ""
    echo "To start manually: sudo systemctl start adcast-player"
    echo "To reboot later:   sudo reboot"
    echo ""
fi
