#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_NAME="rpi-camera-importer"
BIN_PATH="/usr/local/bin/${APP_NAME}"
RUNTIME_DIR="/usr/local/lib/${APP_NAME}"
CONFIG_DIR="/etc/rpi-camera-importer"
CONFIG_FILE="${CONFIG_DIR}/cameras.conf"
UDEV_RULE="/etc/udev/rules.d/99-rpi-camera-importer.rules"
ATTACH_UNIT="/etc/systemd/system/rpi-camera-importer-attach@.service"

require_root() {
  if [[ "${EUID}" -ne 0 ]]; then
    echo "This script must run as root"
    exit 1
  fi
}

install_dependencies() {
  echo "Dependency installation at deploy is disabled."
  echo "Dependencies are checked at runtime by rpi-camera-importer."
}

install_files() {
  install -d /usr/local/bin
  install -d "$RUNTIME_DIR"
  install -d "$CONFIG_DIR"

  install -m 0755 "${SCRIPT_DIR}/scripts/rpi-camera-importer.sh" "$BIN_PATH"
  install -m 0755 "${SCRIPT_DIR}/scripts/rpi-camera-disk-handler.sh" "${RUNTIME_DIR}/rpi-camera-disk-handler.sh"
  install -m 0755 "${SCRIPT_DIR}/scripts/rpi-camera-udev-wrapper.sh" "${RUNTIME_DIR}/rpi-camera-udev-wrapper.sh"
  install -m 0755 "${SCRIPT_DIR}/scripts/autonas-media-importer.sh" "${RUNTIME_DIR}/autonas-media-importer.sh"

  if [[ ! -f "$CONFIG_FILE" ]]; then
    install -m 0644 "${SCRIPT_DIR}/config/cameras.conf" "$CONFIG_FILE"
  else
    echo "Config already exists, preserving: $CONFIG_FILE"
  fi

  install -m 0644 "${SCRIPT_DIR}/config/99-rpi-camera-importer.rules" "$UDEV_RULE"
  install -m 0644 "${SCRIPT_DIR}/config/rpi-camera-importer-attach@.service" "$ATTACH_UNIT"
}

activate() {
  systemctl daemon-reload
  udevadm control --reload-rules
  udevadm trigger --subsystem-match=block --action=add
}

main() {
  require_root
  install_dependencies
  install_files
  activate

  echo "Installed ${APP_NAME}"
  echo "Wizard: ${APP_NAME} wizard"
  echo "Logs: journalctl -u rpi-camera-importer-attach@<UUID>.service -f"
}

main "$@"
