#!/usr/bin/env bash
set -euo pipefail
SERVER="${1:-}"
SERVER="${SERVER%/}"
AUDIO_OUT="${AUDIO_OUT:-auto}"
if [[ $EUID -ne 0 ]]; then echo "Hãy chạy bằng sudo."; exit 1; fi
if [[ ! "$SERVER" =~ ^https:// && ! "$SERVER" =~ ^http://(127\.0\.0\.1|localhost)(:[0-9]+)?$ ]]; then
  echo "Thiếu hoặc sai địa chỉ máy chủ (bắt buộc https://)."
  exit 1
fi
. /etc/os-release
export DEBIAN_FRONTEND=noninteractive
echo "== Cài gói ($PRETTY_NAME)"
apt-get update -q
apt-get install -y -q cage pipewire pipewire-pulse wireplumber pulseaudio-utils alsa-utils \
  python3 ffmpeg fonts-noto-core fonts-noto-color-emoji ca-certificates curl gnupg systemd-timesyncd
if [[ "$ID" == "debian" ]]; then
  apt-get install -y -q chromium
  BROWSER=/usr/bin/chromium
  POLICY_DIR=/etc/chromium/policies/managed
else
  install -d -m 0755 /usr/share/keyrings
  curl -fsSL https://dl.google.com/linux/linux_signing_key.pub | gpg --dearmor --yes -o /usr/share/keyrings/google-chrome.gpg
  echo "deb [arch=amd64 signed-by=/usr/share/keyrings/google-chrome.gpg] https://dl.google.com/linux/chrome/deb/ stable main" \
    > /etc/apt/sources.list.d/google-chrome.list
  apt-get update -q
  apt-get install -y -q google-chrome-stable
  BROWSER=/usr/bin/google-chrome-stable
  POLICY_DIR=/etc/opt/chrome/policies/managed
fi
echo "== Người dùng chạy máy phát"
if ! id jawavex &>/dev/null; then useradd -m -s /usr/sbin/nologin jawavex; fi
for g in audio video render input; do getent group "$g" >/dev/null && usermod -aG "$g" jawavex; done
install -d -o jawavex -g jawavex -m 0750 /var/lib/jawavex
install -d -o jawavex -g jawavex -m 0750 /var/lib/jawavex/tools /var/lib/jawavex/media /var/lib/jawavex/media/tmp
echo "== Cấu hình"
install -d -m 0755 /etc/jawavex /usr/local/lib/jawavex
cat > /etc/jawavex/may-phat.conf <<EOF
SERVER=$SERVER
BROWSER=$BROWSER
AUDIO_OUT=$AUDIO_OUT
EOF
install -d -m 0755 "$POLICY_DIR"
cat > "$POLICY_DIR/jawavex.json" <<EOF
{
  "AutoplayAllowed": true,
  "LocalNetworkAccessAllowedForUrls": ["$SERVER"],
  "InsecurePrivateNetworkRequestsAllowedForUrls": ["$SERVER"],
  "DefaultNotificationsSetting": 2,
  "DefaultGeolocationSetting": 2,
  "TranslateEnabled": false,
  "PasswordManagerEnabled": false,
  "AutofillAddressEnabled": false,
  "BrowserSignin": 0,
  "SyncDisabled": true,
  "MetricsReportingEnabled": false,
  "PromotionalTabsEnabled": false,
  "BackgroundModeEnabled": false,
  "CommandLineFlagSecurityWarningsEnabled": false,
  "HardwareAccelerationModeEnabled": true,
  "AllowFileSelectionDialogs": false,
  "DownloadRestrictions": 3,
  "IncognitoModeAvailability": 1,
  "SavingBrowserHistoryDisabled": true
}
EOF
cat > /usr/local/lib/jawavex/chay-may-phat.sh <<'EOF'
#!/usr/bin/env bash
set -u
. /etc/jawavex/may-phat.conf
PROFILE=/var/lib/jawavex/trinh-duyet

for _ in $(seq 1 20); do pactl info >/dev/null 2>&1 && break; sleep 0.5; done
if pactl info >/dev/null 2>&1; then
  if [[ "$AUDIO_OUT" != "auto" ]]; then
    SINK=$(pactl list short sinks | awk '{print $2}' | grep -i "$AUDIO_OUT" | head -n1 || true)
    [[ -n "$SINK" ]] && pactl set-default-sink "$SINK"
  fi
  pactl set-sink-mute @DEFAULT_SINK@ 0 || true
fi

PREF="$PROFILE/Default/Preferences"
if [[ -f "$PREF" ]]; then
  sed -i 's/"exited_cleanly":false/"exited_cleanly":true/; s/"exit_type":"[^"]*"/"exit_type":"Normal"/' "$PREF" || true
fi

exec cage -d -- "$BROWSER" \
  --kiosk --start-fullscreen --app="$SERVER/player/" \
  --user-data-dir="$PROFILE" \
  --ozone-platform=wayland \
  --autoplay-policy=no-user-gesture-required \
  --noerrdialogs --disable-infobars --no-first-run --no-default-browser-check \
  --disable-session-crashed-bubble --disable-pinch --overscroll-history-navigation=0 \
  --check-for-update-interval=31536000 --password-store=basic \
  --disable-features=Translate,MediaRouter,HardwareMediaKeyHandling \
  --enable-features=VaapiVideoDecodeLinuxGL,VaapiVideoDecoder,AcceleratedVideoDecodeLinuxGL \
  --disk-cache-size=104857600
EOF
chmod 0755 /usr/local/lib/jawavex/chay-may-phat.sh
if [[ -f "$(dirname "$0")/jawavex-agent.py" ]]; then
  install -m 0755 "$(dirname "$0")/jawavex-agent.py" /usr/local/lib/jawavex/jawavex-agent.py
else
  curl -fsSL "$SERVER/tai/jawavex-agent.py" -o /usr/local/lib/jawavex/jawavex-agent.py
  chmod 0755 /usr/local/lib/jawavex/jawavex-agent.py
fi
echo "== Dịch vụ systemd"
cat > /etc/systemd/system/jawavex-player.service <<'EOF'
[Unit]
Description=JaWaveX - máy phát toàn màn hình (cage + trình duyệt kiosk trên tty1)
After=systemd-user-sessions.service network-online.target sound.target
Wants=network-online.target
Conflicts=getty@tty1.service
After=getty@tty1.service

[Service]
User=jawavex
PAMName=login
TTYPath=/dev/tty1
TTYReset=yes
TTYVHangup=yes
TTYVTDisallocate=yes
StandardInput=tty-fail
StandardOutput=journal
StandardError=journal
UtmpIdentifier=tty1
UtmpMode=user
ExecStart=/usr/local/lib/jawavex/chay-may-phat.sh
Restart=always
RestartSec=3

[Install]
WantedBy=graphical.target
EOF
cat > /etc/systemd/system/jawavex-agent.service <<'EOF'
[Unit]
Description=JaWaveX - agent cục bộ của máy phát (127.0.0.1:8765)
After=network.target

[Service]
ExecStart=/usr/bin/python3 /usr/local/lib/jawavex/jawavex-agent.py
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF
cat > /etc/systemd/system/jawavex-reboot.service <<'EOF'
[Unit]
Description=JaWaveX - khởi động lại định kỳ

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl reboot
EOF
cat > /etc/systemd/system/jawavex-reboot.timer <<'EOF'
[Unit]
Description=JaWaveX - khởi động lại định kỳ mỗi Chủ nhật 04:30

[Timer]
OnCalendar=Sun *-*-* 04:30:00

[Install]
WantedBy=timers.target
EOF
echo "== Hệ thống chạy 24/7"
systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target >/dev/null
systemctl enable --now systemd-timesyncd >/dev/null 2>&1 || true
install -d /etc/systemd/system.conf.d
printf '[Manager]\nRuntimeWatchdogSec=30s\n' > /etc/systemd/system.conf.d/jawavex-watchdog.conf
install -d /etc/systemd/journald.conf.d
printf '[Journal]\nSystemMaxUse=200M\n' > /etc/systemd/journald.conf.d/jawavex.conf
systemctl --global enable pipewire.socket pipewire-pulse.socket wireplumber.service >/dev/null 2>&1 || true
systemctl daemon-reload
systemctl set-default graphical.target >/dev/null
systemctl disable getty@tty1.service >/dev/null 2>&1 || true
systemctl enable jawavex-agent.service jawavex-player.service jawavex-reboot.timer >/dev/null
systemctl restart jawavex-agent.service
systemctl restart jawavex-player.service
echo "✓ Đã cài JaWaveX."
