#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x

trigger-builder-install-prune() {
  declare desc="builder install plugin trigger"
  declare trigger="install"

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

[Service]
Type=oneshot
User=$DOKKU_SYSTEM_USER
ExecStart=$DOCKER_BIN builder prune -f

[Install]
WantedBy=docker.service
EOF

    cat <<EOF >/etc/systemd/system/docker-builder-prune.timer
[Unit]
Description=Run docker-builder-prune.service every day at 4:05am

[Timer]
OnCalendar=Mon..Sun 04:05
Persistent=true

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

5 4 * * * $DOKKU_SYSTEM_USER $DOCKER_BIN builder prune >>/var/log/dokku/builder-prune.log 2>&1
EOF
  fi
}

trigger-builder-install-prune "$@"
