#!/bin/sh -e

url="$1"
[ -z "${url}" ] && url="$(pbpaste)"

if ! echo "${url}" | grep -Eq '^https?://'; then
  # echo "${url}" | mdclip
  echo "Not a link"
  exit 1
fi

tmpfile="$(mktemp "${TMPDIR:-/tmp}"/"$(basename "$0")".XXXXXX)"

get_title() {
  # perl/awk/grep: `pup --charset utf-8 --plain 'head title text{}'`
  # curl "$1" -so - | perl -l -0777 -ne 'print $1 if /<title.*?>\s*(.*?)\s*<\/title/si'
  # curl "$1" -so - | awk -v RS='</title' 'RT { gsub(/.*<title[^>]*>/,""); print }'
  curl "$1" -so - | grep -i "<title>" | sed -n 's/.*<title>\(.*\)<\/title>.*/\1/ip;T;q'
}

if echo "${url}" | grep -Eq '^https://github.com/[^/]*/[^/]*/issues'; then
  printf '%s' "${url}" \
    | sed "s|https://github.com/\([^/]*/[^/]*\)/issues/\([0-9]*\)|[\1#\2](${url})|"
elif echo "${url}" | grep -Eq '^https://github.com/[^/]*/[^/]*/pull'; then
  printf '%s' "${url}" \
    | sed "s|https://github.com/\([^/]*/[^/]*\)/pull/\([0-9]*\)|[\1#\2](${url})|"
elif echo "${url}" | grep -Eq '^https://github.com/[^/]*/[^/]*/commit'; then
  printf '%s' "${url}" \
    | sed "s|https://github.com/\([^/]*/[^/]*\)/commit/\([0-9a-z]\{7\}\).*|[\1\@\2](${url})|"
elif echo "${url}" | grep -Eq '^https://github.com/[^/]*/[^/]*/?$'; then
  printf '%s' "${url}" \
    | sed "s|https://github.com/\([^/]*/[^/$]*\)|[\1](${url})|"
else
  title="$(get_title "${url}" | sed 's| - YouTube$||')"
  [ -z "${title}" ] && title="${url}"
  printf "[%s](%s)" "${title}" "${url}"
fi | tee "${tmpfile}" | pbcopy

title="$(cat <"${tmpfile}" | sed 's|.*\[\(.*\)\](.*)|\1|')"
notify "${title}" "${url}"
cat "${tmpfile}"
