#!/bin/bash
# Create a new symlink to today's logs, for ease of browsing.

# Default configuration.
LOGS_DIR="/data/logs"

# Process the directories in the $LOGS_DIR directory.
[[ -d "$LOGS_DIR" ]] && {
  TODAY="$(printf "%(%Y/%m/%d)T")"

  for DIR in "$LOGS_DIR"/*/; do
    cd "$DIR" 2>/dev/null || {
      printf "%s: %s\\n" "${0##*/}" "failed to change directory to '$DIR'" >&2
      ERR=1
      continue
    }

    # Logs are for root only.
    umask 022

    # Create the new days' location.
    # shellcheck disable=SC2174
    mkdir -p -m 0755 "$LOGS_DIR/$TODAY" 2>/dev/null || {
      printf "%s: %s\\n" "${0##*/}" "failed to create directory '$LOGS_DIR/$TODAY'" >&2
      ERR=1
      continue
    }

    # Create the 'today' symlink to the new location.
    ln -sfn "$TODAY" "today" 2>/dev/null || {
      printf "%s: %s\\n" "${0##*/}" "updating 'today' symlink failed in '$DIR'" >&2
      ERR=1
      continue
    }
  done
}

exit "${ERR:-0}"
