#!/bin/bash
#
# Purpose : Save files sent to this computer with Taildrop (tailscale file cp,
#           or Tailscale's apps) to your Downloads folder, and say so in a
#           notification. Run by federated-connector-taildrop.service, which
#           configure tailscale turns on.

dir="$(xdg-user-dir DOWNLOAD 2> /dev/null)"
[ -n "$dir" ] && [ "$dir" != "$HOME" ] || dir="$HOME/Downloads"

# The files tailscale file get --verbose reports writing, one per line
received() {
  sed -nE 's/.*wrote .* as (.*) \([0-9]+ bytes\).*/\1/p' <<< "$1" | xargs -r -d '\n' -n 1 basename
}

notify() {
  local names=() title body action
  mapfile -t names < <(received "$1")
  if (( ${#names[@]} == 1 )); then
    title="Received ${names[0]}"
  elif (( ${#names[@]} > 1 )); then
    title="Received ${#names[@]} files"
    body="$(printf '%s\n' "${names[@]}")"
  else
    title="Received files"
  fi
  action="$(notify-send --app-name=Tailscale --icon=folder-download --action=open="Show" \
    "$title" "${body:-In $(basename "$dir")}")"
  [ "$action" = open ] && xdg-open "$dir"
}

while true; do
  mkdir -p "$dir"
  # Waits for files, saves them, and returns. It fails at once when Tailscale
  # isn't running or this computer is off the network; wait, then try again.
  if output="$(tailscale file get --wait --conflict=rename --verbose "$dir" 2>&1)"; then
    notify "$output" &
  else
    sleep 60
  fi
done
