#!/usr/bin/env bash

### delphi api commandline client
###
### if you persist environment variables to .env
###    envsubst < .env
###
### usage:
###   delphi USQX91801703
###   delphi GRAS_4867
###   delphi isrcToArtistId USQX91801703
###   delphi nameToArtistId "Billy Joel"
###   delphi 'artists?isrc=USQX91801703' '.artist_id'

set -eu

help() {
  grep '^###' ${0}
}
trap 'help' 1 ERR

err() {
  info "$*"
  help
  exit 1
}

info() {
  echo -e "$*" >&2
}

log() {
  echo -e "\n# $*"
}

test -z "$DELPHI_API_URL" && err "Missing DELPHI_API_URL" 
test -z "$DELPHI_API_CLIENT_ID" && err "Missing DELPHI_API_CLIENT_ID" 
test -z "$DELPHI_API_CLIENT_SECRET" && err "missing DELPHI_API_CLIENT_SECRET"

access_token() {
  if [[ ! -s .access_token ]]; then
    info "getting new access token"
    curl --silent --request POST \
    "$DELPHI_API_URL/oauth/token" \
    --header  "accept: application/json" \
    --header  "content-type: application/json" \
    --data "{\"client_id\":\"$DELPHI_API_CLIENT_ID\",\"client_secret\":\"$DELPHI_API_CLIENT_SECRET\",\"grant_type\":\"client_credentials\"}" \
    | jq -r '.access_token' > .access_token
    info "persisted token to .access_token"
  fi

  cat .access_token
}

ACCESS_TOKEN=$(access_token)

[[ -z "$1" ]] && err "missing endpoint or shortcut"

delphi() {
  endpoint="$1"
  selector="${2:-.}"
  options="${3:-}"
  info "-> $endpoint $selector"
  curl --silent \
    --request GET "${DELPHI_API_URL}/$endpoint" \
    --header  "accept: application/json" \
    --header  "authorization: bearer $ACCESS_TOKEN" \
    $options \
   | jq -r "$selector"
}

# add shortcuts here
if [[ $1 =~ ^GRAS_[0-9]+$ ]]; then
    # for some reason, this returns gzip'd, always
    delphi "artists/$1" '.full_name' '--compressed' 2>/dev/null
elif [[ $1 =~ ^[A-Z]+[0-9]+$ ]]; then
    name=$(delphi "tracks?isrc=$1" '.items[0].name' 2>/dev/null)
    artist=$(delphi "artists?isrc=$1" '.items[0].full_name' 2>/dev/null)
    echo "$name - $artist"
elif [[ $1 == isrcToArtistId ]]; then
  delphi "artists?isrc=$2" '.items[0].artist_id'
elif [[ "$1" == "isrcToArtistName" ]]; then
  delphi "artists?isrc=$2" '.items[0].full_name'
elif [[ "$1" == "isrcToTrackName" ]]; then
  delphi "tracks?isrc=$2" '.items[0].name'
elif [[ "$1" == "nameToArtistId" ]]; then
  delphi "search?query=${2/ /\%20}&index=artist" '.items[0].artist_id'
else
  delphi "$*"
fi
