#!/bin/bash

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

if [ -z ${MS_TMPFS_DIR} ]; then
  echo "MS_TMPFS_DIR is not set - using default /var/opt/ms/tmp"
  MS_TMPFS_DIR="/var/opt/ms/tmp"
fi

if [ -z ${MS_INTERNAL_DIR} ]; then
  echo "MS_INTERNAL_DIR is not set - using default /data/ms"
  MS_INTERNAL_DIR="/data/ms"
fi

if [ -z ${MS_EXTERNAL_DIR} ]; then
  echo "MS_EXTERNAL_DIR is not set - using default /srv/ms"
  MS_EXTERNAL_DIR="/srv/ms"
fi

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 "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 $?
}

# clean up MSP log if too big
clean_up_msp_log() {
  local dir=$1
  local ms_log_path="$dir/logs/msp.00.log"

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

usermod -g ${GROUP} ${USER}

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

# External storage available
if (mountpoint -q /srv || is_link /srv) && [ $(get_disk_space /srv) -ge $EXTERNAL_MINIMUM_SPACE ] && (! isSrvReadOnly); then
  if [ ! -d $MS_EXTERNAL_DIR ]; then
    # Create external directory
    mkdir -p "${MS_EXTERNAL_DIR}/logs"
    chown ${USER}:${GROUP} "${MS_EXTERNAL_DIR}"
    chmod -R g+rw "${MS_EXTERNAL_DIR}"
    chown ${USER}:${GROUP} "${MS_EXTERNAL_DIR/logs}"
    chmod -R g+rw "${MS_EXTERNAL_DIR/logs}"
  fi

  if [ -d $MS_INTERNAL_DIR ]; then
    if [ "$(find ${MS_INTERNAL_DIR}/ -maxdepth 1 -mindepth 1 -type d | wc -l)" -gt 0 ]; then
      # Move internal directory to external directory
      rsync -a $MS_INTERNAL_DIR/ $MS_EXTERNAL_DIR/
      rm -rf "${MS_INTERNAL_DIR:?}"/*
    fi
  fi
else
  if [ ! -d $MS_INTERNAL_DIR ]; then
    mkdir -p "${MS_INTERNAL_DIR}/logs"
    chown ${USER}:${GROUP} "${MS_INTERNAL_DIR}"
    chmod -R g+rw "${MS_INTERNAL_DIR}"
    chown ${USER}:${GROUP} "$MS_INTERNAL_DIR/logs"
    chmod -R g+rw "${MS_INTERNAL_DIR}/logs"
  fi
fi

if [ -d ${MS_INTERNAL_DIR} ]; then
  clean_up_msp_log ${MS_INTERNAL_DIR}

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

if [ -d $MS_EXTERNAL_DIR ]; then
  clean_up_msp_log $MS_EXTERNAL_DIR

  chown -c $USER:$GROUP $MS_EXTERNAL_DIR
  chown -c -R $USER:$GROUP $(find $MS_EXTERNAL_DIR -mindepth 1 -maxdepth 1 -type d -printf "%p ") | tail -n 10
fi
