#!/bin/bash
# Minimal bootstrap script for cloud-init first boot (test).
set -e

# Ensure hostname resolves (avoids "sudo: unable to resolve host")
H="$(hostname)"
grep -q "127.0.1.1.*$H" /etc/hosts || echo "127.0.1.1	$H" >> /etc/hosts

# Do not overwrite /etc/resolv.conf: use DNS from DHCP so file.server and LXC DNS work.

# --- Chromium kiosk autostart (same behaviour as gnss-guard start-chromium.sh) ---
PI_USER="${PI_USER:-pi}"
SCRIPT_DEST="/usr/local/bin/start-chromium.sh"
AUTOSTART_SYSTEM="/etc/xdg/autostart"
PI_HOME="/home/$PI_USER"
# Icon: download start-here.png from file server, or set DESKTOP_ICON to override
FILE_SERVER="${FILE_SERVER:-http://file.server:5000/files/first-boot}"
ICON_DEST="/usr/share/pixmaps/tm.png"
DESKTOP_ICON="${DESKTOP_ICON:-chromium-browser}"
if [ "$DESKTOP_ICON" = "chromium-browser" ]; then
  mkdir -p /usr/share/pixmaps
  icon_url="${FILE_SERVER}/start-here.png"
  if ! curl -fsSL "$icon_url" -o "$ICON_DEST" 2>/dev/null; then
    # Fallback: use gateway IP (LXC on provisioning LAN) when DNS not ready yet at first boot
    gw="$(ip -4 route show default 2>/dev/null | awk '{print $3; exit}')"
    if [ -n "$gw" ]; then
      curl -fsSL "http://${gw}:5000/files/first-boot/start-here.png" -o "$ICON_DEST" 2>/dev/null || true
    fi
  fi
  if [ -s "$ICON_DEST" ]; then
    chmod 644 "$ICON_DEST"
    DESKTOP_ICON="$ICON_DEST"
  fi
fi

# Install start-chromium.sh system-wide so it works regardless of user home
cat << 'START_CHROMIUM_EOF' > "$SCRIPT_DEST"
#!/bin/bash
# Disable keyring prompts
export GNOME_KEYRING_CONTROL=""
export DISPLAY=:0

# Force X11 instead of Wayland for better fullscreen support
export GDK_BACKEND=x11
unset WAYLAND_DISPLAY

# Wait for display and desktop environment to be ready
for i in {1..60}; do
    if xset q >/dev/null 2>&1 || [ -n "$DISPLAY" ]; then
        if pgrep -x pcmanfm >/dev/null 2>&1 || pgrep -x lxsession >/dev/null 2>&1 || pgrep -x xfdesktop >/dev/null 2>&1; then
            break
        fi
    fi
    sleep 0.5
done

sleep 5

/usr/bin/chromium --start-fullscreen --noerrdialogs --disable-infobars --disable-session-crashed-bubble --disable-restore-session-state --no-first-run --password-store=basic --use-mock-keychain --ozone-platform=x11 --disable-features=UseChromeOSDirectVideoDecoder --app=http://127.0.0.1:8080 &

sleep 3
for i in {1..10}; do
    WINDOW_ID=$(wmctrl -l 2>/dev/null | grep -i chromium | head -1 | awk '{print $1}')
    if [ -n "$WINDOW_ID" ]; then
        wmctrl -i -r "$WINDOW_ID" -b add,fullscreen 2>/dev/null
        break
    fi
    sleep 0.5
done

wait
START_CHROMIUM_EOF
chmod 755 "$SCRIPT_DEST"

# Autostart entry (runs Chromium at desktop login)
mkdir -p "$AUTOSTART_SYSTEM"
cat > "$AUTOSTART_SYSTEM/chromium-kiosk.desktop" << DESKTOP_EOF
[Desktop Entry]
Type=Application
Name=Chromium Fullscreen
Exec=/usr/local/bin/start-chromium.sh
Icon=$DESKTOP_ICON
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
DESKTOP_EOF
chmod 644 "$AUTOSTART_SYSTEM/chromium-kiosk.desktop"

# Desktop shortcut: real .desktop file on Desktop so the file manager treats it as a launcher (not a script).
# Symlink with no extension was shown as "executable script" and prompted; .desktop runs directly with quick_exec=1.
if getent passwd "$PI_USER" >/dev/null 2>&1; then
  mkdir -p "$PI_HOME/Desktop" "$PI_HOME/.config/libfm"
  if [ -f "$PI_HOME/.config/libfm/libfm.conf" ] && grep -q '^quick_exec=' "$PI_HOME/.config/libfm/libfm.conf"; then
    sed -i 's/^quick_exec=.*/quick_exec=1/' "$PI_HOME/.config/libfm/libfm.conf"
  else
    echo 'quick_exec=1' >> "$PI_HOME/.config/libfm/libfm.conf"
  fi
  chown -R "$PI_USER:$PI_USER" "$PI_HOME/.config/libfm" 2>/dev/null || true
  DESKTOP_FILE="$PI_HOME/Desktop/GNSS Guard.desktop"
  cat > "$DESKTOP_FILE" << DESKTOP_SHORTCUT_EOF
[Desktop Entry]
Type=Application
Name=GNSS Guard
Comment=GNSS Guard Dashboard (e.g. if closed)
Exec=/usr/local/bin/start-chromium.sh
Icon=$DESKTOP_ICON
Terminal=false
Categories=Utility;
DESKTOP_SHORTCUT_EOF
  chmod 644 "$DESKTOP_FILE"
  chown "$PI_USER:$PI_USER" "$DESKTOP_FILE"
  # Remove old symlink if present
  rm -f "$PI_HOME/Desktop/GNSS Guard"
  # Application menu/panel entry (same content)
  SHORTCUT_FILE="/usr/share/applications/gnss-guard.desktop"
  cat > "$SHORTCUT_FILE" << DESKTOP_SHORTCUT_EOF
[Desktop Entry]
Type=Application
Name=GNSS Guard
Comment=GNSS Guard Dashboard (e.g. if closed)
Exec=/usr/local/bin/start-chromium.sh
Icon=$DESKTOP_ICON
Terminal=true
Categories=Utility;
DESKTOP_SHORTCUT_EOF
  chmod 644 "$SHORTCUT_FILE"
fi

echo "[$(date -Iseconds)] test completed" | tee -a /var/log/cloud-init-bootstrap.log
