#!/usr/bin/env bash

set -e

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
MEYECTL=''
while (( $# )); do
  case "$1" in
    '--skip-systemd') SKIP_SYSTEMD=1;;
    '--skip-apt-update') SKIP_APT_UPDATE=1;;
    '--meyectl') (( $# > 1 )) || { echo 'ERROR: Missing path after "--meyectl". Aborting ...'; exit 1; }; MEYECTL=$2; shift;;
    *) echo "ERROR: Invalid command-line argument \"$1\". Aborting ..."; exit 1;;
  esac
  shift
done
if [[ $MEYECTL && ! ( -f $MEYECTL && -x $MEYECTL ) ]]; then
  echo "ERROR: meyectl executable \"$MEYECTL\" given with --meyectl does not exist. Aborting ..."
  exit 1
fi

# 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=''
  TMPDIR=''
  [[ -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' | grep -Po "\"browser_download_url\": *\"\K[^\"]*\/${PI}${DISTRO}_motion_.*_${ARCH}\.deb(?=\")" | head -1)
    if [[ ${URL} ]]
    then
      echo "INFO: Matching package found, downloading: ${URL}"
      TMPDIR=$(mktemp -d)
      if curl -fLo "${TMPDIR}/motion.deb" "${URL}"
      then
        MOTION="${TMPDIR}/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
  [[ $TMPDIR ]] && rm -R "$TMPDIR"
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
# The settings may contain credentials (motion_control_authentication), and motionEye is not supposed to write to this file
chown root:motion /etc/motioneye/motioneye.conf
chmod 0640 /etc/motioneye/motioneye.conf

(( SKIP_SYSTEMD )) && exit 0

# Install service
cp extra/motioneye.systemd /etc/systemd/system/motioneye.service
# - Update meyectl path if given, e.g. by motioneye_init from a venv, or if expected /usr/local/bin/meyectl does not exist, found on Arch Linux: https://github.com/motioneye-project/motioneye/issues/3005
if [[ $MEYECTL || ! -f '/usr/local/bin/meyectl' ]]
then
  if meyectl_path=${MEYECTL:-$(command -v meyectl)}
  then
    echo "Using $meyectl_path for systemd service"
    sed -i "s|^ExecStart=/usr/local/bin/meyectl|ExecStart=$meyectl_path|" /etc/systemd/system/motioneye.service
  else
    echo 'ERROR: meyectl executable has not been found. systemd service will fail to start. Please check your motionEye installation.'
  fi
fi
systemctl daemon-reload
systemctl enable motioneye
systemctl restart motioneye
