#!/bin/bash
PKG="ai-feature-console"
USER="unifi-protect-ai"
GROUP="unifi-protect-ai"
DB_USER="unifi-protect-ai"
DB_PORT=5433
LOGS_DIR="/var/log/$PKG"
EXTERNAL_MINIMUM_SPACE=67108864 # 64 GB

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

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

# clean up ems log if too big
clean_up_ems_log() {
  local dir=$1
  local ems_log_path="$dir/logs/ems.00.log"

  local MAX_SIZE=20971520 # 20 MB
  if [ -f $ems_log_path ]; then
    if [ $(stat -c%s $ems_log_path) -gt $MAX_SIZE ]; then
      rm -f $ems_log_path
    fi
  fi
}

move_log_to_dir() {
  local target_dir="$1"

  mkdir -p "$target_dir"
  if [[ -d "$LOGS_DIR" && $(find "${LOGS_DIR}"/ -maxdepth 1 -mindepth 1 -type f | wc -l) -gt 0 ]]; then
    rsync -a "$LOGS_DIR"/* "$target_dir"
  fi

  if [[ -d "$LOGS_DIR" && "$LOGS_DIR" == *"$PKG"* ]]; then
    rm -rf "$LOGS_DIR"
  fi
  ln -sfn "$target_dir" "$LOGS_DIR"
}

saveJournals() {
  # Check if journalctl is available
  if ! command -v journalctl &> /dev/null; then
      echo "journalctl command not found. Make sure you have systemd installed."
      return 1
  fi

  unit_name="$PKG.service"
  log_file="/tmp/.lastProtectJournal"
  journalctl -u "$unit_name" --since "1 minute ago" > "$log_file"
  chown $USER:$GROUP $log_file

  echo "Journal log saved to $log_file"
}

saveJournals

# External storage available
if (mountpoint -q /srv || is_link /srv) && [ $(get_disk_space /srv) -ge $EXTERNAL_MINIMUM_SPACE ]; then
  if [ ! -d $AITEAM_EXTERNAL_DIR ]; then
    # Create external directory
    mkdir $AITEAM_EXTERNAL_DIR
  fi
  # always chown to prevent folder unexpectedly exists
  chown $USER:$GROUP $AITEAM_EXTERNAL_DIR

  if [ ! -d "$AITEAM_EXTERNAL_DIR/logs" ]; then
    mkdir "$AITEAM_EXTERNAL_DIR/logs"
  fi
    # always chown/chmod to prevent folder unexpectedly exists
  chown -c -R $USER:$GROUP "$AITEAM_EXTERNAL_DIR/logs"

  if !(is_link "$LOGS_DIR" ); then
    move_log_to_dir "$AITEAM_EXTERNAL_DIR/logs"
  fi

  if [ -d $AITEAM_INTERNAL_DIR ]; then
    if [ "$(find ${AITEAM_INTERNAL_DIR}/ -maxdepth 1 -mindepth 1 -type d | wc -l)" -gt 0 ]; then
      # Unmount temp filesystem from internal directory, ignore if not exists
      umount -l $AITEAM_INTERNAL_DIR/temp 2>/dev/null || true

      # Move everything to external directory
      # mv $(find $AITEAM_INTERNAL_DIR -maxdepth 1 -mindepth 1 -type d) $AITEAM_EXTERNAL_DIR
      rsync -a $AITEAM_INTERNAL_DIR/ $AITEAM_EXTERNAL_DIR/

    #   # Do we need to change DB? (only if we are saving something to local?)
    #   # Update DB records, due to we support motion only recording if NVR has buildIn SSD
    #   psql -U $DB_USER -p $DB_PORT -c "UPDATE \"recordingFiles\" SET folder = REPLACE(folder, '/data/unifi-protect', '/srv/unifi-protect')"
    #   psql -U $DB_USER -p $DB_PORT -c "UPDATE \"backupFiles\" SET path = REPLACE(path, '/data/unifi-protect', '/srv/unifi-protect')"
    #   psql -U $DB_USER -p $DB_PORT -c "UPDATE \"updates\" SET path = REPLACE(path, '/data/unifi-protect', '/srv/unifi-protect')"

      # Delete internal directory
      rm -rf "${AITEAM_INTERNAL_DIR:?}"/*
    fi
  fi

#   # Check disk has enough free spaces to start Protect
#   free_spaces=$(df -k /srv | tail -n 1 | awk '{printf $4}')
#   # disk quota hard limit is 32G, set the MIN_SPACES to 33 GB
#   MIN_SPACES=34603008
#   GB=1048576
#   # Do we need to remove something?
#   if [ "${free_spaces}" -lt "${MIN_SPACES}" ]; then
#     num=$(((MIN_SPACES - free_spaces) / GB + 1))
#     find $AITEAM_TBD_DIR -type f -printf '%T+ %p\n' | grep '0_rotating' | sort | head -n ${num} | awk '{print $2}' | xargs rm
#   fi
else
  if [ ! -d $AITEAM_INTERNAL_DIR ]; then
    # Create internal directory
    mkdir $AITEAM_INTERNAL_DIR
  fi
  chown $USER:$GROUP $AITEAM_INTERNAL_DIR

  if [ ! -d "$AITEAM_INTERNAL_DIR/logs" ]; then
    mkdir "$AITEAM_INTERNAL_DIR/logs"
  fi
  chown $USER:$GROUP "$AITEAM_INTERNAL_DIR/logs"

  if !(is_link "$LOGS_DIR" ); then
    move_log_to_dir "$AITEAM_INTERNAL_DIR/logs"
  fi
fi

# Make sure unifi-protect-ai permissions
if [ -d $AITEAM_INTERNAL_DIR ]; then
  clean_up_ems_log $AITEAM_INTERNAL_DIR

  if [ -L $AITEAM_INTERNAL_DIR ]; then
    chown -c -h $USER:$GROUP $AITEAM_INTERNAL_DIR
    chown -c -R $USER:$GROUP $AITEAM_INTERNAL_DIR/ | tail -n 10
  else
    chown -c -R $USER:$GROUP $AITEAM_INTERNAL_DIR | tail -n 10
  fi
fi

if [ -d $AITEAM_EXTERNAL_DIR ]; then
  clean_up_ems_log $AITEAM_EXTERNAL_DIR

  chown -c -R $USER:$GROUP $AITEAM_EXTERNAL_DIR
#   chown -c -R $USER:$GROUP $(find $AITEAM_EXTERNAL_DIR -mindepth 1 -maxdepth 1 -type d -not -path "$AITEAM_EXTERNAL_DIR/cv" -prune -printf "%p ") | tail -n 10
#   find $AITEAM_EXTERNAL_DIR/cv -maxdepth 1 -type d -exec chown -c $USER:$GROUP {} +
fi

# if ! findmnt -t tmpfs -m $AITEAM_TMPFS_DIR 1>&2>/dev/null; then
#   # Mount temp filesystem
#   mount -t tmpfs -o size=$AITEAM_TMPFS_SIZE tmpfs $AITEAM_TMPFS_DIR || true
# fi
