#!/usr/bin/env bash

if (( UID )); then
  echo 'ERROR: Root permissions required. Please run this command as root user, via "sudo" or "su". Aborting...'
  exit 1
fi

# Process CLI arguments
SKIP_SYSTEMD=0
SKIP_APT_UPDATE=0
while (( $# )); do
  case "$1" in
    '--skip-systemd') SKIP_SYSTEMD=1;;
    '--skip-apt-update') SKIP_APT_UPDATE=1;;
    *) echo "ERROR: Invalid command-line argument \"$1\". Aborting..."; exit 1;;
  esac
  shift
done

# Install dependencies
if command -v apt-get > /dev/null; then
  echo 'INFO: APT-based distribution detected, installing motionEye dependencies'
  (( SKIP_APT_UPDATE )) || apt-get update
  # If matching package can be found, install from motion project GitHub releases
  MOTION='motion'
  DISTRO=''
  [[ -f '/etc/os-release' ]] && DISTRO=$(sed -n '/^VERSION_CODENAME=/{s/^[^=]*=//p;q}' /etc/os-release)
  if [[ $DISTRO ]]; then
    ARCH=$(dpkg --print-architecture)
    # On ARMv6 Raspberry Pi models, download armv6hf package
    PI=''
    [[ ${ARCH} == 'armhf' && $(uname -m) == 'armv6l' ]] && PI='pi_'
    echo "INFO: ${DISTRO^} on ${ARCH} detected, checking for latest motion package from GitHub releases"
    command -v curl > /dev/null || DEBIAN_FRONTEND="noninteractive" apt-get -y --no-install-recommends install curl
    URL=$(curl -sSfL 'https://api.github.com/repos/Motion-Project/motion/releases' | awk -F\" "/browser_download_url.*${PI}${DISTRO}_motion_.*_${ARCH}.deb/{print \$4}" | head -1)
    if [[ ${URL} ]]
    then
      echo "INFO: Matching package found, downloading: ${URL}"
      if curl -fLo /tmp/motion.deb "${URL}"
      then
        MOTION='/tmp/motion.deb'
      else
        echo 'WARNING: Download failed, installing (older) motion package from APT repository instead'
      fi
    else
      echo "WARNING: No motion package found for ${DISTRO^} on ${ARCH}, installing from APT repository instead"
    fi
  else
    echo 'WARNING: Distribution version could not be detected, installing motion from APT repository'
  fi
  DEBIAN_FRONTEND="noninteractive" apt-get -y --no-install-recommends install "${MOTION}" v4l-utils ffmpeg curl
  rm -f motion.deb
elif command -v yum > /dev/null; then
  echo 'INFO: YUM-based distribution detected, installing motionEye dependencies'
  yum -y install motion v4l-utils ffmpeg curl
else
  echo 'WARNING: This system uses neither APT nor YUM. Please install these dependencies manually:
  motion v4l-utils ffmpeg curl'
fi

# Stop and disable conflicting motion.service
if systemctl -q is-active motion 2> /dev/null || systemctl -q is-enabled motion 2> /dev/null; then
  systemctl disable --now motion
fi

# Pre-create config and data dirs and install configuration files
if [[ -f '/etc/motioneye/motioneye.conf' ]]
then
  # Update PID file directory if the default from old motionEye is still present: https://github.com/motioneye-project/motioneye/issues/2657
  grep -q '^run_path /var/run$' /etc/motioneye/motioneye.conf && sed -i '\|^run_path /var/run$|c\run_path /run/motioneye' /etc/motioneye/motioneye.conf
else
  [[ -d '/etc/motioneye' ]] || mkdir /etc/motioneye
  cp extra/motioneye.conf.sample /etc/motioneye/motioneye.conf
fi
chown -R motion:motion /etc/motioneye

(( SKIP_SYSTEMD )) && exit 0

# Install service
cp extra/motioneye.systemd /etc/systemd/system/motioneye.service
systemctl daemon-reload
systemctl enable --now motioneye
