#!/bin/bash

endpoint="${PB_ENDPOINT:-https://clip.simd.stream}"
jq_args="${PB_JSON:--r .url}"
private="${PB_PRIVATE:-0}"
clipboard="${PB_CLIPBOARD}"
# clipboard_tool="${PB_CLIPBOARD_TOOL:-xclip}"
clipboard_tool="xclip -selection clipboard"
logfile="${PB_LOGFILE:-$HOME/local/logs/pb.log}"

log_ () {
  tee -a "$logfile"
  echo >> "$logfile"
}

pb_ () {
  local filename extension

  filename="${1:--}"
  extension="${2:-}"

  shift 2

  data=$(curl -sF "file=@$filename" "$@" "$endpoint")

  if [[ ! -z $clipboard ]]; then
    url="$data"
    egrep -q '^url: https?://' <<<"$url" && url="$(awk '/url: / { print $2; }' <<<"$url")"
    printf "${url}" | eval "${clipboard_tool}"
  fi

  echo "${data}" | log_

  if [[ ! -z $clipboard ]]; then
    echo "$(awk '{print $1}' <<<"$clipboard_tool"): Copied to clipboard!"
  fi
}

pb_png () {
  maim -s | pb_ - .png
}

pb_gif () {
  capture gif - | pb_ - .gif
}

pb_webm () {
  capture webm - | pb_ - .webm
}

pb_delete () {
  curl -s -X DELETE https://clip.simd.stream/"$1" | log_
}

pb () {
  local command="$1"

  case $command in
    png)
      shift
      pb_png "$@"
      ;;
    gif)
      shift
      pb_gif "$@"
      ;;
    webm)
      shift
      pb_webm "$@"
      ;;
    private)
      shift
      private=1
      pb_ "$@"
      ;;
    del|delete)
      shift
      pb_delete "$@"
      ;;
    *)
      pb_ "$@"
      ;;
  esac
}

pb "$@"
