#!/usr/bin/env bash

# Devices to check -- if populated and up, no notifications are sent.
readonly DEVICES=()

# COCO Labels
readonly LABEL_PERSON=0
readonly LABEL_CAT=15

# Lockfile to ensure that only one instance of the script is running.
readonly LOCKFILE="/tmp/motion-notify.lock.d"

# yolo26 working directory.
readonly PROJECT="/tmp/yolo26"

# Notification recipient.
readonly RECIPIENT="${NOTIFICATION_RECIPIENT}"

# rsync user and server for backups.
readonly RSYNC_USER="${RSYNC_USER}"
readonly RSYNC_SERVER="${RSYNC_SERVER}"

acquire_lock () {
  while true; do
    if mkdir "${LOCKFILE}"; then
      break;
    fi
    sleep 1
  done
}

check_devices() {
  for device in "${DEVICES[@]}"; do
    if ping -c 1 -w 1 "${device}" &> "/dev/null"; then
      return 0
    fi
  done

  return 255
}

detect_objects() {
  local filepath="$1"

  "${HOME}/.venv/bin/yolo" predict \
			   classes=0 \
			   conf=0.5 \
			   model="${HOME}/yolo26n.pt" \
			   name="motion" \
			   project="${PROJECT}" \
			   save_txt=true \
			   source="$1"
}

notify() {
  local name="$1"

  echo "${HOSTNAME} at $(date '+%Y-%m-%dT%H:%M:%S%:z')" | \
    mutt -a "${PROJECT}/motion/${name}.jpg" \
	 -s "${HOSTNAME}: Motion Detected" \
	 -- "${RECIPIENT}"
}

upload() {
  local name="$1"

  rsync --archive --verbose \
	"${PROJECT}/motion/${name}.jpg" \
	"${RSYNC_USER}@${RSYNC_SERVER}:/photo/${name}.jpg"
}

delete_outdated() {
  local filepath="$1"

  rm -f "$1"
  rm -rf "${PROJECT}"
}

release_lock () {
  rmdir "${LOCKFILE}"
}

main() {
  local filepath="$1"
  local name
  name="$(basename "${filepath}" .jpg)"

  acquire_lock

  # If devices are present, don't notify.
  if (( "${#DEVICES[@]}" )); then
    if check_devices; then
      delete_outdated "${filepath}" "${name}"
      release_lock
      exit 0
    fi
  fi

  detect_objects "${filepath}"

  # Send a notification if we match any labels.
  labels="$(awk '{print $1}' "${PROJECT}/motion/labels/${name}.txt")"
  if echo "${labels}" | grep -qw "${LABEL_PERSON}\|${LABEL_CAT}"; then
    notify "${name}"
  fi

  upload "${name}"

  delete_outdated "${filepath}" "${name}"
  release_lock
}

main "$@"
