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

trigger-scheduler-docker-local-install() {
  declare desc="scheduler-docker-local install plugin trigger"
  declare trigger="install"
  local DOKKU_PATH

  mkdir -p "${DOKKU_LIB_ROOT}/data/scheduler-docker-local"
  chown -R "${DOKKU_SYSTEM_USER}:${DOKKU_SYSTEM_GROUP}" "${DOKKU_LIB_ROOT}/data/scheduler-docker-local"

  fn-plugin-property-setup "scheduler-docker-local"

  echo "%dokku ALL=(ALL) NOPASSWD:/usr/bin/crontab" >"/etc/sudoers.d/dokku-cron"
  chmod "0440" "/etc/sudoers.d/dokku-cron"

  echo "%dokku ALL=(ALL) NOPASSWD:/usr/bin/docker-container-healthchecker" >"/etc/sudoers.d/dokku-docker-container-healthchecker"
  chmod "0440" "/etc/sudoers.d/dokku-docker-container-healthchecker"

  DOKKU_PATH="$(command -v dokku)"

  if [[ $(systemctl 2>/dev/null) =~ -\.mount ]]; then
    cat <<EOF >/etc/systemd/system/dokku-retire.service
[Unit]
Description=Dokku retire service
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
User=$DOKKU_SYSTEM_USER
ExecStart=$DOKKU_PATH ps:retire
SuccessExitStatus=137

[Install]
WantedBy=docker.service
EOF

    cat <<EOF >/etc/systemd/system/dokku-retire.timer
[Unit]
Description=Run dokku-retire.service every 5 minutes

[Timer]
OnCalendar=*:0/5
Persistent=true

[Install]
WantedBy=timers.target
EOF
    if command -v systemctl &>/dev/null; then
      systemctl --quiet reenable dokku-retire
      systemctl --quiet enable dokku-retire.timer
      systemctl --quiet start dokku-retire.timer
    fi
  else
    cat <<EOF >/etc/cron.d/dokku-retire
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bash

*/5 * * * * $DOKKU_SYSTEM_USER $DOKKU_PATH ps:retire >> /var/log/dokku/retire.log 2>&1
EOF
  fi
}

trigger-scheduler-docker-local-install "$@"
