#!/bin/bash

set -euo pipefail

ver=$1
branch=$2
dst=$3
mkdir -p ./tmp
mkdir -p $dst

echo "Generating configs of version $ver"

# pd repo
mkdir -p ./tmp/${ver} && mkdir -p $dst/${ver}
git clone --depth 1 -b $branch https://github.com/tikv/pd.git ./tmp/${ver}/pd
cp ./pd.go.example ./tmp/${ver}/pd/main.go
cp ./dict_helper.go ./tmp/${ver}/pd/dict_helper.go
cd ./tmp/${ver}/pd && go mod tidy && go run .
cd ../../..
cp ./tmp/${ver}/pd/pd.json $dst/$ver/pd.json
cp ./tmp/${ver}/pd/pd_tso.json $dst/$ver/pd_tso.json
cp ./tmp/${ver}/pd/pd_scheduling.json $dst/$ver/pd_scheduling.json

# tidb repo
mkdir -p ./tmp/${ver} && mkdir -p $dst/${ver}
git clone --depth 1 -b $branch https://github.com/pingcap/tidb.git ./tmp/${ver}/tidb
cp ./tidb.go.example ./tmp/${ver}/tidb/main.go
cp ./dict_helper.go ./tmp/${ver}/tidb/dict_helper.go
# old config package path
if [[ $ver == "v6.1" || $ver == "v6.5" || $ver == "v7.1" ]]; then
  sed -i 's|github.com/pingcap/tidb/pkg/config|github.com/pingcap/tidb/config|g' ./tmp/${ver}/tidb/main.go
  sed -i 's|github.com/pingcap/tidb/pkg/lightning/config|github.com/pingcap/tidb/br/pkg/lightning/config|g' ./tmp/${ver}/tidb/main.go
elif [[ $ver == "v7.5" ]]; then
  sed -i 's|github.com/pingcap/tidb/pkg/lightning/config|github.com/pingcap/tidb/br/pkg/lightning/config|g' ./tmp/${ver}/tidb/main.go
fi
cd ./tmp/${ver}/tidb && go mod tidy && go run .
cd ../../..
cp ./tmp/${ver}/tidb/tidb.json $dst/$ver/tidb.json
cp ./tmp/${ver}/tidb/tidb-lightning.json $dst/$ver/tidb-lightning.json

# tiflow repo
mkdir -p ./tmp/${ver} && mkdir -p $dst/${ver}
git clone --depth 1 -b $branch https://github.com/pingcap/tiflow.git ./tmp/${ver}/tiflow
cp ./tiflow.go.example ./tmp/${ver}/tiflow/main.go
cp ./dict_helper.go ./tmp/${ver}/tiflow/dict_helper.go
cd ./tmp/${ver}/tiflow && go mod tidy && go run .
cd ../../..
cp ./tmp/${ver}/tiflow/ticdc.json $dst/$ver/ticdc.json
