#!/bin/sh -e
#
# unfuckurl - unwrap and url-decode safelinks
# copy the real url to the clipboard and echo for confirmation
# dependencies: trurl

if [ "$#" -eq 0 ]; then
  if [ -t 1 ]; then
    set -- $(pbpaste) || exit
  else
    echo "Usage: ${0##*/} URLs..." >&2
    exit 2
  fi
fi

orig="${1:-/dev/stdin}"
cleanurl=$(trurl --url "${orig}" --qtrim "utm_*" --qtrim "att_*" \
  --qtrim "?__goaway_challenge*" --get "{url}")
ret="$?"
if [ "${ret}" -eq 0 ]; then
  printf '%b' "${cleanurl}" | pbcopy
  pbpaste
fi
