#!/usr/bin/env bash

set -euo pipefail

LOG_TAG="rpi-camera-wrapper"
export PATH="/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/sbin:/usr/sbin"
export HOME="/root"
export USER="root"
export LOGNAME="root"
export SHELL="/bin/bash"
umask 022

action="${1:-}"
uuid="${2:-}"

if [[ -z "$action" || -z "$uuid" ]]; then
  logger -p local0.err -t "$LOG_TAG" "Invalid arguments: action='$action' uuid='$uuid'"
  exit 1
fi

logger -p local0.info -t "$LOG_TAG" "Called with action=$action uuid=$uuid"

(
  sleep 3
  if [[ "$(id -u)" != "0" ]]; then
    logger -p local0.err -t "$LOG_TAG" "Not running as root"
    exit 1
  fi

  if [[ "$action" == "attach" ]]; then
    systemctl start "rpi-camera-importer-attach@${uuid}.service"
    logger -p local0.info -t "$LOG_TAG" "Started attach service for UUID=$uuid"
  else
    logger -p local0.warning -t "$LOG_TAG" "Unsupported wrapper action: $action"
  fi
) &

logger -p local0.info -t "$LOG_TAG" "Background job started for $action $uuid"
exit 0
