#!/bin/sh
# Query local syncthing REST API
subscript="$(which "$(basename $0)-$1" 2>/dev/null)"
if test -f "$subscript"
then shift && $subscript "$@"
else
  apikey=$(grep apikey $XDG_CONFIG_HOME/syncthing/config.xml | cut -d '>' -f2 | cut -d '<' -f1)
  case "$1" in
    (browse|need)
      for arg in "${@:2}"
      do case "$arg" in ([0-9]) depth=$arg;; (*) path="$arg";; esac
      done
      query="db/$1?folder=$(test -n "$path" && echo "${path%%/*}" || echo "data")&levels=${depth:-1}$(case "$path" in (*/*) echo "&prefix=${path#*/}";; esac)";;
    (*) query="$1";;
  esac
  shift
  curl --silent -H 'Content-Type: application/json' -H "X-API-Key: $apikey" "http://localhost:8384/rest/$query" "$@" | bat --style=numbers -l json
fi