#!/bin/bash
[[ $# -lt 2 ]] && { >&2 echo "Usage: $0 <gencfg group> <tag>"; exit 1; }

set -x

GROUP=$1 
TAG=$2

FNAME=$(echo "${GROUP}#${TAG}" | sed -e 's:[/-]:_:g' -e 's:#:-:g')

if [[ -s ${FNAME}.json ]]; then
    echo "Will use cached data from ${FNAME}.json"
else
    for retry in $(seq 0 9); do
        curl -kgm 10 "https://api.gencfg.yandex-team.ru/${TAG}/searcherlookup/groups/$GROUP/instances" > ${FNAME}.json
        [[ $? -eq 0 ]] && break
    done
    [[ -s ${FNAME}.json ]] || exit 1
fi

set -e

cat ${FNAME}.json | jq -r '.instances[] | ( .hostname as $host | .port as $port | .tags | map(. as $tag | ["\($host):\($port)", $tag]) ) | .[] | @csv' | \
    fgrep OPT_shardid | sed -e 's:",":\t:g' -e 's:=:&\t:g' | tr -d \" | sort > shards-${FNAME}.tsv

echo -e '\e[92mDone:\e[0m'" shards-${FNAME}.tsv"

