#!/bin/bash
#
# Purpose : Files' right-click Scripts > "Send with Tailscale": send the
#           selected files with Taildrop to a computer you choose on your
#           Tailscale network. system/taildrop.sh installs it in Nautilus'
#           scripts folder. Also works from a terminal:
#             send-with-tailscale file...

files=()
if [ -n "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" ]; then
  mapfile -t files <<< "${NAUTILUS_SCRIPT_SELECTED_FILE_PATHS%$'\n'}"
else
  files=("$@")
fi

fail() {
  notify-send --app-name=Tailscale --icon=dialog-error "$1" "$2"
  exit 1
}

regular=()
for file in "${files[@]}"; do
  [ -f "$file" ] && regular+=("$file")
done
(( ${#regular[@]} > 0 )) || fail "Nothing to send" "Taildrop sends files, not folders. Choose files."

# Lines of "address<TAB>name" for the computers that can take files
mapfile -t targets < <(tailscale file cp --targets 2> /dev/null)
(( ${#targets[@]} > 0 )) \
  || fail "No computer to send to" "None of your computers on your Tailscale network is online to take files."

rows=()
for target in "${targets[@]}"; do
  IFS=$'\t' read -r address name _ <<< "$target"
  rows+=("$name" "$address")
done
address="$(zenity --list --title="Send with Tailscale" --text="Send ${#regular[@]} file(s) to:" \
  --column=Computer --column=Address --print-column=2 --hide-column=2 --height=360 "${rows[@]}")" || exit 0
[ -n "$address" ] || exit 0
for (( i = 1; i < ${#rows[@]}; i += 2 )); do
  [ "${rows[$i]}" = "$address" ] && name="${rows[$((i - 1))]}"
done

if error="$(tailscale file cp --update-interval=0 -- "${regular[@]}" "$address:" 2>&1)"; then
  if (( ${#regular[@]} == 1 )); then
    notify-send --app-name=Tailscale --icon=document-send "Sent to $name" "$(basename "${regular[0]}")"
  else
    notify-send --app-name=Tailscale --icon=document-send "Sent to $name" "${#regular[@]} files"
  fi
else
  fail "Couldn't send to $name" "$error"
fi
