#!/bin/sh

# Source kiosk configuration: base file first, then drop-ins shipped by
# application packages (later files override earlier ones)
KIOSK_URL=
KIOSK_STATE_DIR=
if [ -f /etc/mymo-kiosk.conf ]; then
    . /etc/mymo-kiosk.conf
fi
for _conf in /etc/mymo-kiosk.conf.d/*.conf; do
    if [ -f "$_conf" ]; then
        . "$_conf"
    fi
done

# Record the URL this session started with so kiosk-refresh can tell
# whether a restart is needed
printf 'KIOSK_URL=%s\n' "$KIOSK_URL" > /tmp/mymo-kiosk.urls

# Application integration, when the application package declares its state
# directory via KIOSK_STATE_DIR:
#  - share the X authority so the application backend can control the
#    display (rotate screen, remap touch input) without needing sudo
#  - restore the rotation the application last saved
SCREEN_ROTATION=normal
if [ -n "$KIOSK_STATE_DIR" ] && [ -d "$KIOSK_STATE_DIR" ]; then
    cp "$HOME/.Xauthority" "$KIOSK_STATE_DIR/xauthority" 2>/dev/null || true
    SCREEN_ROTATION=$(cat "$KIOSK_STATE_DIR/screen-rotation" 2>/dev/null || echo normal)
fi

# Start window manager
openbox &

# Primary output: first connected output reported by xrandr. Match on
# " connected" only — the primary output reads "connected primary WxH..."
# so requiring a digit after "connected" would miss it.
PRIMARY_OUTPUT=$(xrandr --query | awk '/ connected/ {print $1; exit}')

# Apply saved screen rotation
if [ -n "$PRIMARY_OUTPUT" ] && [ "$SCREEN_ROTATION" != "normal" ]; then
    xrandr --output "$PRIMARY_OUTPUT" --rotate "$SCREEN_ROTATION"
    sleep 1
fi

# Touch coordinate transformation matrix matching the screen rotation
case "$SCREEN_ROTATION" in
    left)     TOUCH_MATRIX="0 -1 1 1 0 0 0 0 1" ;;
    right)    TOUCH_MATRIX="0 1 0 -1 0 1 0 0 1" ;;
    inverted) TOUCH_MATRIX="-1 0 1 0 -1 1 0 0 1" ;;
    *)        TOUCH_MATRIX="1 0 0 0 1 0 0 0 1" ;;
esac

# Apply the matrix to every pointer device that supports it — touchscreens
# don't always have "touch" in their name (e.g. "ILITEK ILITEK-TP")
xinput list 2>/dev/null | grep "slave *pointer" | grep -v XTEST \
        | grep -oE 'id=[0-9]+' | cut -d= -f2 | while read -r _dev; do
    if xinput list-props "$_dev" 2>/dev/null | grep -q "Coordinate Transformation Matrix"; then
        xinput set-prop "$_dev" "Coordinate Transformation Matrix" $TOUCH_MATRIX 2>/dev/null || true
    fi
done

# Start audio if available
if command -v pulseaudio >/dev/null 2>&1; then
    pulseaudio --start 2>/dev/null &
fi

# Extract geometry (WxH+X+Y) for a given output
parse_geometry() {
    xrandr --query | awk -v out="$1" '$1 == out && / connected / {
        for (i=1; i<=NF; i++)
            if (match($i, /^[0-9]+x[0-9]+\+[0-9]+\+[0-9]+$/)) { print $i; exit }
    }'
}

# Common Chromium flags. Touch-related flags prevent pinch-zoom, swipe-back,
# and pull-to-refresh, which would break the kiosk experience on a
# touchscreen. check-for-update-interval suppresses update prompts.
CHROMIUM_FLAGS="--kiosk --incognito --no-first-run --noerrdialogs --disable-infobars \
 --disable-pinch --overscroll-history-navigation=0 --disable-pull-to-refresh-effect \
 --disable-features=TranslateUI,TouchpadOverscrollHistoryNavigation,OverscrollHistoryNavigation \
 --disable-component-update --check-for-update-interval=31536000 \
 --autoplay-policy=no-user-gesture-required --disable-smooth-scrolling"

# Run Chromium in a restart loop
# Usage: run_chromium URL WIDTH HEIGHT DATA_DIR
run_chromium() {
    _url="$1"
    _w="$2"
    _h="$3"
    _datadir="$4"

    while true; do
        if [ -n "$_url" ] && case "$_url" in file://*) false;; *) true;; esac; then
            # Wait for the URL to respond
            until curl -s -o /dev/null -w '%{http_code}' "$_url" 2>/dev/null | grep -q 200; do
                sleep 2
            done
        fi

        chromium --window-size="${_w},${_h}" --window-position=0,0 \
            --user-data-dir="$_datadir" \
            $CHROMIUM_FLAGS \
            "$_url"
        sleep 1
    done
}

# Determine target URL
if [ -n "$KIOSK_URL" ]; then
    PRIMARY_URL="$KIOSK_URL"
else
    PRIMARY_URL="file:///usr/share/mymo-kiosk/no-app.html"
fi

# Detect resolution (after rotation, so width/height reflect orientation)
if [ -n "$PRIMARY_OUTPUT" ]; then
    GEOM=$(parse_geometry "$PRIMARY_OUTPUT")
else
    # Fallback: use xdpyinfo
    GEOM=$(xdpyinfo 2>/dev/null | awk '/dimensions/{print $2}')
fi

WIDTH=$(echo "${GEOM:-1024x768}" | sed 's/x.*//')
HEIGHT=$(echo "${GEOM:-1024x768}" | sed 's/.*x//; s/+.*//')

run_chromium "$PRIMARY_URL" "$WIDTH" "$HEIGHT" /tmp/chromium-1
