#!/bin/bash

tag=$1
dst=$2
tmp="./tmp"
tici_branch="${TICI_DASHBOARD_BRANCH:-master}"
mkdir -p $dst
mkdir tmp

git clone --depth 1 -b $tag https://github.com/pingcap/tidb.git $tmp/tidb
cp $tmp/tidb/pkg/metrics/grafana/*.json $dst/
cp $tmp/tidb/metrics/grafana/*.json $dst/
cp $tmp/tidb/br/metrics/grafana/*.json $dst/

git clone --depth 1 -b $tag https://github.com/tikv/pd.git $tmp/pd
cp $tmp/pd/metrics/grafana/*.json $dst/

git clone --depth 1 -b $tag https://github.com/tikv/tikv.git $tmp/tikv
cp $tmp/tikv/metrics/grafana/*.json $dst/

git clone --depth 1 -b $tag https://github.com/pingcap/tiflash.git $tmp/tiflash
cp $tmp/tiflash/metrics/grafana/*.json $dst/

git clone --depth 1 -b $tag https://github.com/pingcap/tidb-binlog.git $tmp/tidb-binlog
cp $tmp/tidb-binlog/metrics/grafana/*.json $dst/

git clone --depth 1 -b $tag https://github.com/pingcap/tiflow.git $tmp/tiflow
cp $tmp/tiflow/metrics/grafana/*.json $dst/

if [ $tag=="master" ]; then
    git clone --depth 1 -b main https://github.com/pingcap/TiProxy.git $tmp/TiProxy
    cp $tmp/TiProxy/pkg/metrics/grafana/tiproxy_summary.json $dst/
else
    git clone --depth 1 -b $tag https://github.com/pingcap/TiProxy.git $tmp/TiProxy
    cp $tmp/TiProxy/pkg/metrics/grafana/tiproxy_summary.json $dst/
fi  

git clone --depth 1 -b master https://github.com/pingcap/monitoring.git $tmp/monitoring
cp $tmp/monitoring/platform-monitoring/ansible/grafana/*.json $dst/

git clone --depth 1 -b $tag https://github.com/pingcap/ticdc.git $tmp/ticdc
cp $tmp/ticdc/metrics/grafana/*.json $dst/

case "$dst" in
    *tidb-dashboards/v8.5.0|*tidb-dashboards/v8.5.x)
        git clone --depth 1 -b "$tici_branch" https://github.com/pingcap-inc/tici.git $tmp/tici
        cp $tmp/tici/grafana/tici_meta.json $dst/
        cp $tmp/tici/grafana/tici_reader.json $dst/
        cp $tmp/tici/grafana/tici_worker.json $dst/
        ;;
esac

rm -rf $tmp
