#!/usr/bin/env bash
set -Eeuo pipefail

usage() {
  red "Missing argument <${1}>.\n"
  cat <<EOF
Usage:
    pastebin.sh <FULL_TITLE>

    Arguments:
      FULL_TITLE       Full title of the pastebin

Examples:
    pastebin.sh 'My example pastebin title'
EOF
}

FULL_TITLE="${1:-}"
[[ -z "${FULL_TITLE}" ]] && {
  usage 'FULL_TITLE'
  exit 2
}

# Derived from:
# https://stackoverflow.com/questions/4009281/how-can-i-generate-url-slugs-in-perl/4009519#4009519
slugify() {
  echo "${1}"                   | \
    tr '[:upper:]' '[:lower:]'  | \
    perl -ne 'tr/\000-\177//cd;
              s/[^\w\s-]//g;
              s/^\s+|\s+$//g;
              s/[-\s]+/-/g;
              print;'
}

SLUG_TITLE="$(slugify "${FULL_TITLE}")"
PASTE_DATE="$(date -I)"
OUT="_pastebins/${PASTE_DATE}-${SLUG_TITLE}.md"

pushd ~/dev/libre/website > /dev/null

[[ -f "${OUT}" ]] && {
  red "Pastebin named ${OUT} already exists."
  exit 1
}

cat <<EOF | vipe | sponge > "${OUT}"
---
title: ${FULL_TITLE}
date: ${PASTE_DATE}
layout: pastebin
lang: en
---

\`\`\`FIXME
FIXME
\`\`\`
EOF

git reset .
git add "${OUT}"
git commit -m "$0: Auto-add ${OUT}"
git push
popd > /dev/null
