Luigit
repositories / bugabinga.net

bugabinga.net

personal infrastructure for bugabinga!

owned by admin

scripts/local/setup-pufferpanel-mail.sh

Raw
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
secret="${repo_root}/keys/pufferpanel-email.env"
mailbox="games@bugabinga.net"
[[ "$#" -eq 0 ]] || exit 2
umask 077
exists="$(ssh -T -o BatchMode=yes box 'curl --fail --silent --show-error --config <(printf "user = \"%s:\"\n" "$(cat /var/lib/mailinabox/api.key)") "http://127.0.0.1:10222/mail/users?format=json"' | jq --arg email "${mailbox}" 'if type == "array" and all(.[]; (.users | type) == "array") then [.[] | .users[] | select(.email == $email)] | length else error("Unexpected mailbox response") end')"
if [[ ! -f "${secret}" ]]; then
  [[ "${exists}" == 0 ]] || {
    echo "Mailbox already exists; supply its credentials without resetting it." >&2
    exit 1
  }
  mkdir -p "${repo_root}/keys"
  password="$(openssl rand -hex 32)"
  (
    set -o noclobber
    printf '%s\n' \
      'PUFFER_PANEL_EMAIL_PROVIDER=smtp' \
      'PUFFER_PANEL_EMAIL_HOST=box.bugabinga.net' \
      "PUFFER_PANEL_EMAIL_FROM=${mailbox}" \
      "PUFFER_PANEL_EMAIL_USERNAME=${mailbox}" \
      "PUFFER_PANEL_EMAIL_PASSWORD=${password}" >"${secret}"
  )
fi
[[ "$(stat -c %a "${secret}")" == 600 ]] || {
  echo "SMTP credential file must have mode 0600." >&2
  exit 1
}
password="$(sed -n 's/^PUFFER_PANEL_EMAIL_PASSWORD=//p' "${secret}")"
[[ "${password}" =~ ^[a-f0-9]{64}$ ]] || {
  echo "Unexpected SMTP credential format." >&2
  exit 1
}
if [[ "${exists}" == 0 ]]; then
  printf '%s' "${password}" | ssh -T -o BatchMode=yes box \
    'curl --fail --silent --show-error --config <(printf "user = \"%s:\"\n" "$(cat /var/lib/mailinabox/api.key)") --data-urlencode email=games@bugabinga.net --data-urlencode password@- --data-urlencode privileges= http://127.0.0.1:10222/mail/users/add'
fi
# Credentials travel through a private fd, not process argv or diagnostic output.
curl --fail --silent --show-error --ssl-reqd --url smtps://box.bugabinga.net:465 \
  --config <(printf 'user = "games@bugabinga.net:%s"\n' "${password}") \
  --mail-from "${mailbox}" --mail-rcpt "${mailbox}" \
  --upload-file <(printf 'From: %s\r\nTo: %s\r\nSubject: PufferPanel SMTP verification\r\nDate: %s\r\n\r\nDedicated PufferPanel mailbox SMTP TLS authentication and delivery verification.\r\n' "${mailbox}" "${mailbox}" "$(date -R)")
printf '%s\n' "Mailbox ${mailbox} configured; SMTP TLS authentication and submission passed."
printf '%s\n' "Private credentials: ${secret}; never commit or publish."