#!/bin/bash

CONFIG_FILE="/opt/kioskApp/config.env"
if [ ! -f "$CONFIG_FILE" ]; then
  echo "❌ Config file not found: $CONFIG_FILE"
  exit 1
fi
source "$CONFIG_FILE"

HOSTNAME=$(hostname)
URL="$SERVER_URL/$ROUTER_SCRIPT?hostname=$HOSTNAME&auth_key=$API_KEY"
echo "[INFO] URL lancée = \$URL" >> /opt/kioskApp/kiosk.log

MODE_DEBUG=true

open_hour=__OPEN_HOUR__
close_hour=__CLOSE_HOUR__
sunday_enabled=__SUNDAY_ENABLED__

current_hour=$(date +%H)
current_day=$(date +%u)  # 1 = lundi, 7 = dimanche

is_sunday=$([ "$current_day" -eq 7 ] && echo 1 || echo 0)
should_run=0

if [ "$is_sunday" -eq 1 ]; then
  [ "$sunday_enabled" -eq 1 ] && should_run=1
else
  if [ "$current_hour" -ge "$open_hour" ] && [ "$current_hour" -lt "$close_hour" ]; then
    should_run=1
  fi
fi

if [ "$MODE_DEBUG" = true ]; then
  echo "[DEBUG] Hour: $current_hour, Sunday: $is_sunday, Should Run: $should_run"
fi

if [ "$should_run" -eq 1 ]; then
  if ! pgrep chromium > /dev/null; then
    [ "$MODE_DEBUG" = true ] && echo "[DEBUG] Starting Chromium..."
    /usr/bin/chromium-browser --kiosk --noerrdialogs --disable-infobars --user-data-dir=/tmp/chromium "$URL" &
  else
    [ "$MODE_DEBUG" = true ] && echo "[DEBUG] Chromium already running."
  fi
else
  if pgrep chromium > /dev/null; then
    [ "$MODE_DEBUG" = true ] && echo "[DEBUG] Stopping Chromium (out of hours)."
    pkill chromium
  fi
fi
