#!/usr/bin/env sh
set -eu

APP_USER="${APP_USER:-saleculator}"
APP_GROUP="${APP_GROUP:-$APP_USER}"
INSTALL_DIR="${INSTALL_DIR:-/opt/saleculator}"
CONFIG_DIR="${CONFIG_DIR:-/etc/saleculator}"
ENABLE_KIOSK=0

usage() {
    cat <<EOF
Usage: $0 [--enable-kiosk]

Installs Saleculator files for a minimal Debian/Raspberry Pi appliance.

Environment overrides:
  APP_USER       default: saleculator
  INSTALL_DIR    default: /opt/saleculator
  CONFIG_DIR     default: /etc/saleculator

--enable-kiosk copies the systemd kiosk service template but does not reboot.
EOF
}

while [ "$#" -gt 0 ]; do
    case "$1" in
        --enable-kiosk)
            ENABLE_KIOSK=1
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        *)
            echo "Unknown option: $1" >&2
            usage >&2
            exit 2
            ;;
    esac
    shift
done

if [ "$(id -u)" -ne 0 ]; then
    echo "Run as root: sudo $0 [--enable-kiosk]" >&2
    exit 1
fi

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
ROOT_DIR=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)
CONFIG_SAMPLE="$ROOT_DIR/config/Saleculator.properties.sample"

if [ ! -f "$CONFIG_SAMPLE" ]; then
    CONFIG_SAMPLE="$ROOT_DIR/src-pos/com/posics/pos/Saleculator.properties"
fi

if [ ! -f "$ROOT_DIR/dist/Saleculator.jar" ]; then
    echo "Missing dist/Saleculator.jar. This runtime package is incomplete; reinstall or replace it with a validated package." >&2
    exit 1
fi

if [ ! -f "$CONFIG_SAMPLE" ]; then
    echo "Missing Saleculator.properties sample config." >&2
    exit 1
fi

if ! id "$APP_USER" >/dev/null 2>&1; then
    useradd --system --create-home --shell /bin/bash "$APP_USER"
fi

mkdir -p "$INSTALL_DIR" "$CONFIG_DIR"
cp -R "$ROOT_DIR/dist" "$ROOT_DIR/lib" "$ROOT_DIR/scripts" "$INSTALL_DIR/"
chmod 755 "$INSTALL_DIR/scripts/"*.sh

if [ ! -f "$CONFIG_DIR/Saleculator.properties" ]; then
    cp "$CONFIG_SAMPLE" "$CONFIG_DIR/Saleculator.properties"
    chown "$APP_USER:$APP_GROUP" "$CONFIG_DIR/Saleculator.properties"
    chmod 600 "$CONFIG_DIR/Saleculator.properties"
fi

chown -R "$APP_USER:$APP_GROUP" "$INSTALL_DIR"

usermod -a -G dialout,lp "$APP_USER" 2>/dev/null || true
if getent group gpio >/dev/null 2>&1; then
    usermod -a -G gpio "$APP_USER" || true
fi

if [ "$ENABLE_KIOSK" -eq 1 ]; then
    cp "$ROOT_DIR/deploy/linux/saleculator-kiosk.service" /etc/systemd/system/saleculator-kiosk.service
    systemctl daemon-reload
    systemctl enable saleculator-kiosk.service
    echo "Kiosk service enabled. Reboot after configuring $CONFIG_DIR/Saleculator.properties."
else
    echo "Installed to $INSTALL_DIR."
    echo "Configure $CONFIG_DIR/Saleculator.properties, then run:"
    echo "  sudo $0 --enable-kiosk"
fi
