#!/bin/bash
#
# Gives /var/spool/ucs to ucs user, after UCS stopped running as root. The spool may be huge (e-mails),
# so ucs-server's after-install.sh runs this in background: journalctl -u ucs-spool-chown
#
# E-mails (email/<queue>/<year>/<month>/...) are processed newest month first, so UCS can store new
# e-mails soon. Queue and year directories are changed last: while root owns them, ucs can't replace
# them with symlinks redirecting chown. Only files owned by root are changed, symlinks aren't followed.

spool=/var/spool/ucs
email=$spool/email
marker=$spool/.owned-by-ucs

if [ -e "$marker" ]; then
  echo "Already done ($marker exists)"
  exit 0
fi

echo "Changing owner of $spool to ucs"

# Everything except e-mails is small, UCS appends to files directly in the spool
find "$spool" -mindepth 1 -maxdepth 1 ! -name email -exec chown -R -h --from=root ucs:ucs {} +

if [ -d "$email" ]; then
  find "$email" -mindepth 3 -maxdepth 3 -type d -printf '%P\n' | sort -t/ -k2,2nr -k3,3nr |
    while read -r month; do
      echo "E-mails $month"
      chown -R -h --from=root ucs:ucs "$email/$month"
    done

  # Files outside of month directories, then queue and year directories bottom-up
  find "$email" -mindepth 1 -maxdepth 3 ! -type d -exec chown -h --from=root ucs:ucs {} +
  find "$email" -depth -mindepth 1 -maxdepth 2 -type d -exec chown -h --from=root ucs:ucs {} +
  chown -h --from=root ucs:ucs "$email"
fi

touch "$marker"
echo "Done"
