#!/usr/bin/env sh
#
# Select a file and share it through 0x0.st
#
# Examples:
# `sharefile`
#   calling without arguments allows you to first select a folder and then
#   a file from the folder to share.
# `sharefile ~/my-file.zip`
#   calling with a file as argument automatically uploads the file and copies
#   share link to clipboard.
# When called with a folder as argument allows you to select file within, uploads it and copies share link.

OXO_URL="https://0x0.st"

folderpicker() {
  selected=$(find "${1:-$HOME}" -type d | fzf)
  [ "$?" -eq 130 ] && exit 130
  echo "$selected"
}

filepicker() {
  selected=$(find "${1:-$HOME}" -type f | fzf)
  [ "$?" -eq 130 ] && exit 130
  echo "$selected"
}

filetooxo() {
  curl -F"file=@$1" "$OXO_URL"
}

# exit on escape pressed
exit_check() {
  [ "$1" -eq 130 ] && exit 130
}

main() {
  if [ $# -eq 0 ]; then
    foldpick=$(folderpicker "")
    exit_check $?
    picked=$(filepicker "$foldpick")
  elif [ -f "$1" ]; then
    picked="$1"
  elif [ -d "$1" ]; then
    picked=$(filepicker "$1")
  else
    printf "Please only provide a folder or file as the optional argument to sharefile." >&2
    exit 1
  fi
  exit_check $?

  url=$(filetooxo "$picked")
  echo "$url"
  if command -v notify-send >/dev/null; then
    notify-send "Upload finished" "URL: $url"
  fi
  # printf "%s" "$url" | nohup xclip -i -selection clipboard -r -verbose -loops 2 >/dev/null 2>&1
  printf "%s" "$url" | xsel --clipboard
  exit
}

main "$@"