#!/bin/bash

version=$(dpkg-query -W -f='${Version}' ds 2>/dev/null) 
echo "#-> ds pre-start: DS $version"

USER="ds"
GROUP="unifi-streaming"
EXTERNAL_MINIMUM_SPACE=54683238



if [ -z ${DS_INTERNAL_DIR} ]; then
  echo "ds pre-start: DS_INTERNAL_DIR is not set - using default /data/ds"
  DS_INTERNAL_DIR="/data/ds"
fi

if [ -z ${DS_EXTERNAL_DIR} ]; then
  echo "ds pre-start: DS_EXTERNAL_DIR is not set - using default /srv/ds"
  DS_EXTERNAL_DIR="/srv/ds"
fi

if [ -z ${PROTECT_INTERNAL_DIR} ]; then
  echo "ds pre-start: PROTECT_INTERNAL_DIR is not set - using default /data/unifi-protect"
  PROTECT_INTERNAL_DIR="/data/unifi-protect"
fi

if [ -z ${PROTECT_EXTERNAL_DIR} ]; then
  echo "ds pre-start: PROTECT_EXTERNAL_DIR is not set - using default /srv/unifi-protect"
  PROTECT_EXTERNAL_DIR="/srv/unifi-protect"
fi

usermod -g ${GROUP} ${USER}

is_link() {
  [ -L "${1}" ] && [ -e "${1}" ] && return
  false
}

get_disk_space() {
  df "${1}" -k | tail -n 1 | awk '{printf $2}'
}

isSrvReadOnly() {
  if ! command -v findmnt &> /dev/null; then
    # ignore if findmnt not found
    return 1
  fi
  # report RO state only if target mounted
  echo "ds pre-start: Read Only file system check" 
  local TMP=$(findmnt --target /srv -o SOURCE,OPTIONS -n)
  echo ${TMP}
  echo ${TMP} | grep -E '^ro$|,ro$|,ro,|^ro,| ro'
  return ${?}
}

setup_directory() {
  local dir=${1}

  if [ -z "${dir}" ]; then
    echo "ds pre-start: ERROR: Directory parameter is empty in setup_directory"
    return 1
  fi

  if [ ! -d "${dir}" ]; then
    echo "ds pre-start: Creating directory ${dir}"
    mkdir -p "${dir}/logs" || true
    chown "${USER}:${GROUP}" "${dir}" || true
    echo "ds pre-start: Chowning directory ${dir}"
    chmod -R g+rw "${dir}" || true
    echo "ds pre-start: Chmoding directory ${dir}"
    chown "${USER}:${GROUP}" "${dir}/logs" || true
    echo "ds pre-start: Chowning logs directory ${dir}/logs"
    chmod -R g+rw "${dir}/logs" || true
    echo "ds pre-start: Chmoding logs directory ${dir}/logs"
  fi
}

setup_cv_analytics_directory() {
  local dir=${1}

  if [ -z "${dir}" ]; then
    echo "ds pre-start: ERROR: Directory parameter is empty in setup_cv_analytics_directory"
    return 1
  fi

  echo "ds pre-start: CV analytics directory ${dir}/cv/analytics-v1"

  # Ensure parent directory exists
  if [ ! -d "${dir}/cv" ]; then
    mkdir -p "${dir}/cv" || true
    echo "ds pre-start: Created parent directory ${dir}/cv"
  fi

  # Ensure target directory exists
  if [ ! -d "${dir}/cv/analytics-v1" ]; then
    mkdir -p "${dir}/cv/analytics-v1" || true
    echo "ds pre-start: Created new directory ${dir}/cv/analytics-v1"
  fi

  # Only change ownership of the specific directories, not contents
  echo "ds pre-start: Changing owner for ${dir}/cv and ${dir}/cv/analytics-v1 directories only (not files) to ${USER}:${GROUP}"
  if [ -d "${dir}/cv" ]; then
    chown "${USER}:${GROUP}" "${dir}/cv" || true
  fi
  if [ -d "${dir}/cv/analytics-v1" ]; then
    chown "${USER}:${GROUP}" "${dir}/cv/analytics-v1" || true
  fi

  # Only set permissions on the directories themselves
  echo "ds pre-start: Setting group permissions for ${dir}/cv and ${dir}/cv/analytics-v1 directories only (not files)"
  if [ -d "${dir}/cv" ]; then
    chmod ug+rw "${dir}/cv" || true
  fi
  if [ -d "${dir}/cv/analytics-v1" ]; then
    chmod ug+rw "${dir}/cv/analytics-v1" || true
  fi
  echo "ds pre-start: CV analytics directory ${dir}/cv/analytics-v1 setup ok"
}

if [ -d "/etc" ]; then
  mkdir -p /etc/ms || true
  chown -R "${USER}:${GROUP}" /etc/ds || true
  chmod -R ug+rw /etc/ds || true
fi

if (mountpoint -q /srv || is_link /srv) && [ $(get_disk_space /srv) -ge ${EXTERNAL_MINIMUM_SPACE} ] && (! isSrvReadOnly); then
  echo "ds pre-start: External directory /srv is writable and has enough space"
  setup_directory "${DS_EXTERNAL_DIR}"
  setup_cv_analytics_directory "${PROTECT_EXTERNAL_DIR}"

  if [ -d ${DS_INTERNAL_DIR} ]; then
    echo "ds pre-start: Checking if internal directory ${DS_INTERNAL_DIR} has any subdirectories"
    if [ "$(find ${DS_INTERNAL_DIR}/ -maxdepth 1 -mindepth 1 -type d | wc -l)" -gt 0 ]; then
      echo "ds pre-start: Rsyncing internal directory ${DS_INTERNAL_DIR} to external directory ${DS_EXTERNAL_DIR}"
      rsync -a ${DS_INTERNAL_DIR}/ ${DS_EXTERNAL_DIR}/
      echo "ds pre-start: Removing all files from internal directory ${DS_INTERNAL_DIR}"
      rm -rf "${DS_INTERNAL_DIR:?}"/*
    fi
  fi
else
  echo "ds pre-start: External directory /srv is not writable or does not have enough space"
  setup_directory "${DS_INTERNAL_DIR}"
  setup_cv_analytics_directory "${PROTECT_INTERNAL_DIR}"
fi

if [ -d ${DS_INTERNAL_DIR} ]; then
  if [ -L ${DS_INTERNAL_DIR} ]; then
    chown -c -h "${USER}:${GROUP}" ${DS_INTERNAL_DIR}
    chown -c -R "${USER}:${GROUP}" ${DS_INTERNAL_DIR}/ | tail -n 10
  else
    chown -c -R "${USER}:${GROUP}" ${DS_INTERNAL_DIR} | tail -n 10
  fi
fi

if [ -d ${DS_EXTERNAL_DIR} ]; then
  chown -c "${USER}:${GROUP}" ${DS_EXTERNAL_DIR}
  chown -c -R "${USER}:${GROUP}" $(find ${DS_EXTERNAL_DIR} -mindepth 1 -maxdepth 1 -type d -printf "%p ") | tail -n 10
fi

echo "<-# ds pre-start: DS $version"
