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

if [[ ! -f "$DOKKU_ROOT/VHOST" ]] && [[ -n "$(dig +short "$(hostname -f)")" ]]; then
  if [[ -d "$DOKKU_ROOT" ]] || [[ -L "$DOKKU_ROOT" ]]; then
    hostname -f >"$DOKKU_ROOT/VHOST"
  fi
fi

dokku_path="$(command -v dokku)"

# temporary hack for https://github.com/dokku/dokku/issues/82
# redeploys all apps after a reboot
if [[ $(/sbin/init --version 2>/dev/null) =~ upstart ]]; then
  cat <<EOF >/etc/init/dokku-redeploy.conf
description "Dokku app redeploy service"

start on filesystem and started docker

script
  sleep 2 # give docker some time
  sudo -i -u dokku $dokku_path ps:restore --parallel -1
end script
EOF
fi

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

[Service]
Type=simple
User=dokku
ExecStart=$dokku_path ps:restore --parallel -1

[Install]
WantedBy=docker.service
EOF
  if command -v systemctl &>/dev/null; then
    systemctl --quiet reenable dokku-redeploy
  fi
fi

mkdir -p /etc/update-motd.d
cat <<DOKKU_EOF >/etc/update-motd.d/99-dokku
#!/bin/sh

if [ ! -s "$DOKKU_ROOT/VHOST" ]; then
cat <<'EOF'

 ! If using virtualhost routing is desired (eg. my-app => my-app.dokku.me), set a global domain for your server:

     dokku domains:set-global dokku.me
EOF
fi

if [ ! -s "$DOKKU_ROOT/.ssh/authorized_keys" ]; then
cat <<'EOF'

 ! Setup a user's ssh key for deployment by passing in the public ssh key as shown:

     echo 'CONTENTS_OF_ID_RSA_PUB_FILE' | dokku ssh-keys:add admin
EOF
fi

if [ ! -f "$DOKKU_ROOT/VHOST" ] ||  [ ! -s "$DOKKU_ROOT/.ssh/authorized_keys" ]; then
cat <<'EOF'

EOF
fi
DOKKU_EOF
chmod +x /etc/update-motd.d/99-dokku

if [[ -f "$DOKKU_ROOT/VHOST" ]]; then
  chown dokku:dokku "$DOKKU_ROOT/VHOST"
fi
