#!/usr/bin/env bash
# =============================================================================
# Install Google Chrome + Wine + Winbox + a web-accessible remote desktop
# (Xvfb + openbox + x11vnc + noVNC) on the Atlas Cyber Protect box.
#
# The owner opens Winbox / Chrome *on the box* and views them from the Atlas
# server through a browser (noVNC) — never on customer PCs.
#
#   sudo bash install-desktop-tools.sh
#
# After install the remote desktop is live at:  http://<box-ip>:6080/vnc.html
# =============================================================================
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Need root: sudo bash $0"
  exit 1
fi

WINBOX_VER="${WINBOX_VER:-3.41}"
WINBOX_URL="https://download.mikrotik.com/routeros/winbox/${WINBOX_VER}/winbox64.exe"
WINBOX_DIR="/opt/atlas-cyber-protect/winbox"
WINEPREFIX_DIR="/var/lib/atlas-cyber-protect/wine"
VNC_PASS_FILE="/var/lib/atlas-cyber-protect/vnc-password.txt"
STATE_DIR="/var/lib/atlas-cyber-protect"

echo "=== Atlas Cyber Protect: installing remote desktop tools ==="
apt-get update -y

# 1) Virtual display + window manager + VNC + noVNC web viewer
echo "--- X stack + VNC + noVNC ---"
apt-get install -y xvfb openbox x11vnc xdotool novnc websockify || true

# 2) Wine (Winbox is a Windows .exe)
echo "--- Wine ---"
apt-get install -y wine wine64 winetricks || true

# 3) Google Chrome (stable .deb straight from Google)
echo "--- Google Chrome ---"
if ! command -v google-chrome-stable >/dev/null 2>&1; then
  TMP_DEB="$(mktemp --suffix=.deb)"
  if curl -fsSL -o "$TMP_DEB" https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb; then
    apt-get install -y "$TMP_DEB" || dpkg -i "$TMP_DEB" || true
    apt-get install -y -f || true
  fi
  rm -f "$TMP_DEB"
fi

# 4) Winbox64 (MikroTik router admin)
echo "--- Winbox ---"
mkdir -p "$WINBOX_DIR"
if [[ ! -f "$WINBOX_DIR/winbox64.exe" ]]; then
  curl -fsSL -o "$WINBOX_DIR/winbox64.exe" "$WINBOX_URL" || true
fi

# 5) Initialize the Wine prefix once (non-interactive: skip mono/gecko popups)
echo "--- Wine prefix ---"
mkdir -p "$WINEPREFIX_DIR"
export WINEPREFIX="$WINEPREFIX_DIR"
export WINEDLLOVERRIDES="mscoree,mshtml="
export WINEDEBUG=-all
wineboot -u >/dev/null 2>&1 || true
wineboot -i >/dev/null 2>&1 || true

# 6) VNC password (random, retrievable by the owner through the authed portal)
if [[ ! -f "$VNC_PASS_FILE" ]]; then
  install -d -m 700 "$STATE_DIR"
  < /dev/urandom tr -dc 'A-HJ-NP-Za-km-z2-9' | head -c 14 > "$VNC_PASS_FILE"
  chmod 600 "$VNC_PASS_FILE"
fi
VNC_PASS="$(cat "$VNC_PASS_FILE")"
x11vnc -storepasswd "$VNC_PASS" /etc/atlas-cyber-protect/vnc-passwd >/dev/null 2>&1 || true
chmod 600 /etc/atlas-cyber-protect/vnc-passwd 2>/dev/null || true

# 7) Remote-desktop launcher + systemd service
echo "--- Remote desktop service ---"
cat >/usr/local/sbin/atlas-cyber-protect-desktop <<'EOF'
#!/bin/bash
# Supervise the Protect box remote desktop: Xvfb -> openbox -> x11vnc -> noVNC.
set -uo pipefail
DISPLAY_NUM=":1"
RES="1280x800x24"
WINEPREFIX_DIR="/var/lib/atlas-cyber-protect/wine"
WINBOX_DIR="/opt/atlas-cyber-protect/winbox"
CHROME_PROFILE="/var/lib/atlas-cyber-protect/chrome-profile"

cleanup() { pkill -f "Xvfb ${DISPLAY_NUM}" 2>/dev/null || true; }
trap cleanup EXIT

# Virtual framebuffer (the "screen" the owner sees over noVNC)
Xvfb "$DISPLAY_NUM" -screen 0 "$RES" -nolisten tcp &
sleep 1
export DISPLAY="$DISPLAY_NUM"

# Lightweight window manager so windows can move/resize
openbox >/dev/null 2>&1 &
sleep 1

# Pre-open the two tools so the owner lands straight into them
google-chrome-stable --no-sandbox --disable-gpu --disable-dev-shm-usage \
  --user-data-dir="$CHROME_PROFILE" about:blank >/dev/null 2>&1 &
export WINEPREFIX="$WINEPREFIX_DIR"
export WINEDLLOVERRIDES="mscoree,mshtml="
export WINEDEBUG=-all
if [[ -f "$WINBOX_DIR/winbox64.exe" ]]; then
  wine "$WINBOX_DIR/winbox64.exe" >/dev/null 2>&1 &
fi

# VNC server (loopback only) + noVNC web viewer on :6080
x11vnc -display "$DISPLAY_NUM" -forever -shared -rfbauth /etc/atlas-cyber-protect/vnc-passwd \
  -listen 127.0.0.1 -rfbport 5901 >/dev/null 2>&1 &
sleep 1

exec websockify --web=/usr/share/novnc 0.0.0.0:6080 127.0.0.1:5901
EOF
chmod +x /usr/local/sbin/atlas-cyber-protect-desktop

cat >/etc/systemd/system/atlas-cyber-protect-desktop.service <<'EOF'
[Unit]
Description=Atlas Cyber Protect remote desktop (Chrome + Winbox via noVNC)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/sbin/atlas-cyber-protect-desktop
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now atlas-cyber-protect-desktop.service || true

LAN_IP="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src"){print $(i+1); exit}}' || echo "<box-ip>")"
echo
echo "=== Done. Remote desktop is live. ==="
echo "  noVNC URL:   http://${LAN_IP}:6080/vnc.html"
echo "  VNC password: $(cat "$VNC_PASS_FILE")"
echo "  (the password is also available to the owner through the portal)"
