#!/bin/sh
#
# xgo - test and open a clipboard URL with an apt program
# run xgo(1d) with the contents of the clipboard `xgo "$(wl-copy)"`

self=xgo

# Check arguments
if [ "$#" -eq 0 ]; then
  printf >&2 'xgo: At least one URL required\n'
  exit 2
fi

# Iterate over the URL arguments
for url; do
  (

    notify-send "${self}: Loading ${url}..."

    # Look for patterns in the URL that suggest transformations
    # shellcheck disable=SC2249
    case ${url} in

      # If this is a GitHub or GitLab link, swap "blob" for "raw" to get the
      # actual file
      *://github.com/*/blob/* | *://gitlab.com/*/blob/*)
        url=$(printf '%s\n' "${url}" | sed 's_/blob/_/raw/_')
        ;;

      # Dig out the plain text for pastebin.com links
      *://pastebin.com/*)
        # shellcheck disable=SC2016
        url=$(printf '%s\n' "${url}" | sed 's_/[A-Za-z0-9][A-Za-z0-9]*$_/raw&_')
        ;;

      # If this is a not-direct imgur link and not to an album, swap URL
      # elements to get to the actual file (it may not actually be a JPEG;
      # the MIME type will tell us)
      *://imgur.com/a/*) ;;
      *://imgur.com/*)
        url=$(printf '%s\n' "${url}" | sed 's_imgur\.com_i.imgur.com_;s/$/.jpg/')
        ;;
    esac

    # If this is a YouTube video without a given start time, load it in mpv(1)
    # shellcheck disable=SC2249
    case ${url} in
      *[/.]youtube.com/watch*[?\&]t=) ;;
      *[/.]youtube.com/watch*)
        exec mpv \
          --force-window \
          --terminal=no \
          --x11-name="${self}" \
          -- "${url}"
        ;;
    esac

    # Get the MIME type data
    mt=$(urlmt "${url}")

    # Switch on media type
    case ${mt} in

      # Open PDFs in mupdf(1); download them first as mupdf(1) does not seem
      # to have a way to handle stdin files
      application/pdf)
        (
          cd -- "${HOME}"/Downloads || exit
          curl -O -- "${url}" || exit
          exec mupdf -- "${url##*/}"
        )
        ;;

      # Open audio and video in mpv(1)
      audio/* | video/*)
        exec mpv \
          --force-window \
          --terminal=no \
          --x11-name="${self}" \
          -- "${url}"
        ;;

      # Open GIFs with a looping mpv(1), and all other images with feh(1)
      image/gif)
        exec mpv \
          --force-window \
          --loop=inf \
          --terminal=no \
          --x11-name="${self}" \
          -- "${url}"
        ;;
      image/*)
        feh --class="${self}" \
          --geometry=640x480 \
          --image-bg=black \
          --scale-down \
          -- "${url}"
        ;;

      # Open plain text in a terminal view(1)
      text/plain)
        # shellcheck disable=SC2016
        exec x-terminal-emulator -name "${self}" \
          -e sh -c 'curl -- "$1" | view -' _ "${url}"
        ;;

      # Otherwise, just pass it to br(1d)
      *)
        exec br "${url}"
        ;;
    esac

  ) &
done
