#!/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 $?
}

# chown only when the current owner:group differs from the desired one.
# chown() always rewrites the inode (bumping ctime), so skipping the syscall
# on already-correct entries is a real I/O saving on large trees.
chown_if_needed() {
  local spec=$1 target=$2
  [ -e "$target" ] || return 0
  local current
  current=$(stat -L -c '%U:%G' "$target" 2>/dev/null) || return 0
  [ "$current" = "$spec" ] && return 0
  chown "$spec" "$target"
}

# Same as chown_if_needed but for the symlink itself (no dereference).
chown_link_if_needed() {
  local spec=$1 target=$2
  [ -L "$target" ] || return 0
  local current
  current=$(stat -c '%U:%G' "$target" 2>/dev/null) || return 0
  [ "$current" = "$spec" ] && return 0
  chown -h "$spec" "$target"
}

# Recursive chown that touches only entries whose owner or group does not
# already match. Spec may be "user:group" or ":group".
chown_r_if_needed() {
  local spec=$1
  shift
  local u="${spec%%:*}"
  local g="${spec#*:}"
  [ "$u" = "$spec" ] && g=""
  local conds=()
  if [ -n "$u" ] && [ -n "$g" ]; then
    conds=( '(' '!' -user "$u" -o '!' -group "$g" ')' )
  elif [ -n "$u" ]; then
    conds=( '!' -user "$u" )
  elif [ -n "$g" ]; then
    conds=( '!' -group "$g" )
  else
    return 0
  fi
  local t
  for t in "$@"; do
    [ -e "$t" ] || continue
    find "$t" "${conds[@]}" -exec chown -h "$spec" {} + 2>/dev/null
  done
}

# 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_if_needed "${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_if_needed "${USER}:${GROUP}" "${MS_EXTERNAL_DIR}" || true
    chmod -R g+rw "${MS_EXTERNAL_DIR}"
    chown_if_needed "${USER}:${GROUP}" "${MS_EXTERNAL_DIR}/logs" || true
    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_if_needed "${USER}:${GROUP}" "${MS_INTERNAL_DIR}" || true
    chmod -R g+rw "${MS_INTERNAL_DIR}"
    chown_if_needed "${USER}:${GROUP}" "$MS_INTERNAL_DIR/logs" || true
    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_link_if_needed "$USER:$GROUP" "$MS_INTERNAL_DIR" || true
    chown_r_if_needed "$USER:$GROUP" "$MS_INTERNAL_DIR/" || true
  else
    chown_r_if_needed "$USER:$GROUP" "$MS_INTERNAL_DIR" || true
  fi
fi

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

  chown_if_needed "$USER:$GROUP" "$MS_EXTERNAL_DIR" || true
  mapfile -d '' EXTERNAL_SUBDIRS < <(find "$MS_EXTERNAL_DIR" -mindepth 1 -maxdepth 1 -type d -print0)
  if [ ${#EXTERNAL_SUBDIRS[@]} -gt 0 ]; then
    chown_r_if_needed "$USER:$GROUP" "${EXTERNAL_SUBDIRS[@]}" || true
  fi
fi
