#!/usr/bin/env bash

API_BASE="https://gitlab.com/api/v4"
SCOPE="groups"
ID="$GROUP"
SUB="$2"
SUB_DESC="${3:-Project}"

if [[ -z "$GROUP" ]]; then
  SCOPE="users"
  ID=$(curl "$API_BASE/user" | jq '.id')
fi

if [[ -z $(which jq) ]]; then
  echo '{"items":[{"title":"Please install jq","subtitle":"Select this to open instructions","arg":"https://stedolan.github.io/jq/download/"}]}'
else
  if [[ ! -d ".cache" ]]; then
    mkdir .cache
  fi

  query=$1
  hash=$(echo $query | md5 -q)

  fl=".cache/projects-$hash.json"

  if [[ ! -f $fl ]]; then
    url="$API_BASE/$SCOPE/$ID/projects?private_token=$TOKEN&include_subgroups=true&per_page=20&search=$query"
    curl $url >$fl
  fi

  url_build=$([[ -z "$SUB" ]] && echo ".web_url" || echo '([.web_url, "/-/'$SUB'"] | join(""))')
  jquery='map({title: (["Open '$SUB_DESC': ",.path] | join("")), subtitle: .path_with_namespace, arg:'$url_build'}) | {items:.}'

  jq "$jquery" $fl
fi
