#!/usr/bin/env bash
set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"

DOKKU_RSYSLOG_FILTER_DIR=/etc/rsyslog.d
DOKKU_RSYSLOG_FILTER=$DOKKU_RSYSLOG_FILTER_DIR/99-dokku.conf
DOKKU_LOGROTATE_FILE=/etc/logrotate.d/dokku

flag_rsyslog_needs_restart=n

# This can be done unconditionally as mkdir -p
# exits gracefully if the path already exists
mkdir -m 775 -p "$DOKKU_LOGS_DIR"
case "$DOKKU_DISTRO" in
  arch|debian)
    chgrp dokku "$DOKKU_LOGS_DIR"
    ;;
  *)
    chown syslog:dokku "$DOKKU_LOGS_DIR"
    ;;
esac

if [[ ! -f  "$DOKKU_EVENTS_LOGFILE" ]]; then
  touch "$DOKKU_EVENTS_LOGFILE"
  case "$DOKKU_DISTRO" in
    arch|debian)
      chgrp dokku "$DOKKU_EVENTS_LOGFILE"
      ;;
    *)
      # chown syslog:root might not work on SUSE
      chown syslog:dokku "$DOKKU_EVENTS_LOGFILE"
      ;;
  esac
  chmod 664 "$DOKKU_EVENTS_LOGFILE"
fi

if [[ -d "$DOKKU_RSYSLOG_FILTER_DIR" && ! -f  "$DOKKU_RSYSLOG_FILTER" ]]; then
  cat >"$DOKKU_RSYSLOG_FILTER" <<EOF
:syslogtag, contains, "dokku" $DOKKU_EVENTS_LOGFILE
EOF
  flag_rsyslog_needs_restart=y
fi

if [[ ! -f "$DOKKU_LOGROTATE_FILE" ]]; then
  cat >"$DOKKU_LOGROTATE_FILE" <<EOF
$DOKKU_LOGS_DIR/*.log {
        daily
        rotate 7
        missingok
        notifempty
        su syslog dokku
        compress
        delaycompress
        postrotate
                reload rsyslog >/dev/null 2>&1 || true
        endscript
        create 664 syslog dokku
}
EOF

  if [[ "$DOKKU_DISTRO" = "debian" ]]; then
    sed -i '/\s*su syslog dokku/d; s/\(create [0-7][0-7][0-7]\) syslog dokku/\1 root dokku/g' $DOKKU_LOGROTATE_FILE
  fi

  flag_rsyslog_needs_restart=y
fi

if [[ -f "$DOKKU_RSYSLOG_FILTER" && "$flag_rsyslog_needs_restart" == "y" ]]; then
  service rsyslog restart
fi

[[ ! "$DOKKU_EVENTS" ]] || dokku_log_plugn_trigger_call "$(basename "$0")" "$@"

exit 0
