#!/bin/bash


DEST=${3:-"$PWD/conf"}
BACKUP=$DEST/backup
DEPLOY=$BACKUP/deploy
WORKDEPLOY=$DEST/deploy



if [ -d $BACKUP ]; then
  echo "Directory $BACKUP already exist; please backup"
  exit;
fi

if [ -d $WORKDEPLOY ]; then
  echo "Directory $WORKDEPLOY already exist; please backup"
  exit;
fi


flag=true
read -p "Please input validator count:" N
while $flag
do
   expr $N + 0 &>/dev/null
   [ $? -eq 0 ] && flag=false || read -p "please input validator count as integer:" N
done


ipAddrs=()

for i in $(seq 1 $N)
do

while read -p  "please input validator $i ip address:"  addr
do
if [[ "$addr" =~ ^(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))$ ]]; then
  ipAddrs=(${ipAddrs[@]} $addr)
  break
else
  echo "invalid ip addr: $addr"
fi
done
done
#echo ${ipAddrs[@]}



flag=true
read -p "please input a chain-id:" chainId
while $flag
do
   expr $chainId + 0 &>/dev/null
   [ $? -eq 0 ] && flag=false || read -p "please input a chain-id as integer:" chainId
done



genesisAccountList=()
declare -A accountMapAmount


allFlag=true

while $allFlag
do
accflag=true
flag=true
read -p "please add genesis account:" account
while $accflag
do
    if [[ -z $account ]]; then echo "You pressed ENTER with no input text" && flag=false && accflag=false && allFlag=false  && break ; fi
    account="${account,,}"
    if [[ "$account" =~ ^[0-9a-f]{40}$ ]] || [[ "$account" =~ ^0x[0-9a-f]{40}$ ]] ; then
      read -p "please input amount for $account:" amount
      while $flag
      do
      # echo $account
      # echo $amount

      if [[  $amount =~ ^[1-9][0-9]*[0-9]?$ ]] ; then 
      if [[ -z $amount ]]; then echo "You pressed ENTER with no input text" && flag=false && accflag=false && allFlag=false  && break  ; fi
        flag=false
        accflag=false

        genesisAccountList=(${genesisAccountList[@]} $account)
        accountMapAmount[$account]=$amount

      else    
        read -p "please input a valid amount for $account:" amount
      fi 
      done
    else
      read -p "please add a valid genesis account:" account
    fi
done
done




flag=true
read -p "Please input sync node count:" syncN
while $flag
do
   expr $syncN + 0 &>/dev/null
   [ $? -eq 0 ] && flag=false || read -p "please input sync node count as integer:" syncN
done



rm -rf ~/.cmp*
cmpcli config keyring-backend test
cmpcli config chain-id $chainId
cmpcli config output json
cmpcli config indent true
cmpcli config trust-node true



#8545 rest server unlock addr
cmpcli keys add restunlock

for i in $(seq 1 $N)
do
      cmpcli keys add mykey$i
      dest=$DEPLOY/node$i
      mkdir -p $dest
      echo "Generating and init node dir for node$i"
      cmpd init node$i --chain-id $chainId --home $dest
done


mainDest=$DEPLOY/node1
# echo ${genesisAccountList[@]}
# echo ${!accountMapAmount[@]}
# echo ${accountMapAmount[@]}

for i in "${!genesisAccountList[@]}";
do
    # printf "%s\t------------%s \n"  "${genesisAccountList[$i]}"  "${accountMapAmount[${genesisAccountList[$i]}]}"
     demon="cmp"
     coin="${accountMapAmount[${genesisAccountList[$i]}]}$demon"
     cmpd add-genesis-account ${genesisAccountList[$i]} $coin,1coin0,1coin1,1coin2,1coin3,1coin4 --home $mainDest
done


Node1Dir=""

for i in $(seq 1 $N)
do
  dest=$DEPLOY/node$i
  ipaddr=${ipAddrs[$(($i-1))]}

   cmpd add-genesis-account $(cmpcli keys show mykey$i -a) 1000000000000000000cmp,1coin0,1coin1,1coin2,1coin3,1coin4 --home $dest
   cmpd gentx --name mykey$i --home $dest --ip $ipaddr  --node-id $(cmpd metaversegraph show-node-id --home $dest) --keyring-backend test --amount 1000000000000000000cmp

    if [ $i -eq 1 ] ; then
      Node1Dir=$dest
      cmpd add-genesis-account $(cmpcli keys show restunlock -a) 1cmp,1coin0,1coin1,1coin2,1coin3,1coin4 --home $dest

      genesisAccountList=(${genesisAccountList[@]} $(cmpcli keys show restunlock -a))
      accountMapAmount[$(cmpcli keys show restunlock -a)]=1
    else
      cp $dest/config/gentx/*  $Node1Dir/config/gentx/
      cmpd add-genesis-account $(cmpcli keys show mykey$i -a) 1000000000000000000cmp,1coin0,1coin1,1coin2,1coin3,1coin4 --home $Node1Dir
    fi

    genesisAccountList=(${genesisAccountList[@]} $(cmpcli keys show mykey$i -a))
    accountMapAmount[$(cmpcli keys show mykey$i -a)]=1000000000000000000

done


cmpd collect-gentxs --home $Node1Dir


for i in $(seq 1 $N)
do
    dest=$DEPLOY/node$i
    if [ $i -ne 1 ] ; then
      rm -f $dest/config/genesis.json
      cp $Node1Dir/config/genesis.json  $dest/config/
    fi
done

os=`uname -a`
mac='Darwin'

for i in $(seq 1 $N)
do
  dest=$DEPLOY/node$i
  if [[ $os =~ $mac ]];then
        gsed -i 's/addr_book_strict = true/addr_book_strict = false/g' $dest/config/config.toml
        gsed -i 's/"max_validators": 100,/"max_validators": '$N',/g' $dest/config/genesis.json
    else
      sed -i 's/addr_book_strict = true/addr_book_strict = false/g' $dest/config/config.toml
      sed -i 's/"max_validators": 100,/"max_validators": '$N',/g' $dest/config/genesis.json
  fi
done



mkdir -p $BACKUP/clicfg.all.address
cp -R ~/.cmpcli/* $BACKUP/clicfg.all.address

mkdir -p $BACKUP/clicfg
mkdir -p $BACKUP/clicfg/keyring-test-cmp

unlockAddr=$(cmpcli  keys parse  $(cmpcli keys  show  restunlock  -a |awk '{print substr ($0, 3)}') | jq .formats[0] |  sed 's/.\(.*\)/\1/' | sed 's/\(.*\)./\1/')

addrFileEndStr=".address"
cp -R ~/.cmpcli/config/  $BACKUP/clicfg/config/
cp -R ~/.cmpcli/keyring-test-cmp/$unlockAddr$addrFileEndStr $BACKUP/clicfg/keyring-test-cmp/
cp -R ~/.cmpcli/keyring-test-cmp/restunlock.info $BACKUP/clicfg/keyring-test-cmp/
rm -rf ~/.cmpcli/

for i in $(seq 1 $N)
do
    dest=$DEPLOY/node$i
    cp -R $BACKUP/clicfg  $dest 
done

rm -rf $BACKUP/clicfg


offsetN=$N 
endN=$(($offsetN + $syncN))

for i in $(seq $(($offsetN+1)) $endN)
do
      dest=$DEPLOY/node$i
      mkdir -p $dest
      echo "Generating and init node dir for node$i"
      cmpd init node$i --chain-id $chainId --home $dest

done



Node1Dir=$DEPLOY/node1
for i in $(seq  $(($offsetN+1)) $endN)
do
    dest=$DEPLOY/node$i
    if [ $i -ne 1 ] ; then
      rm -f $dest/config/genesis.json
      rm -f $dest/config/config.toml
      cp $Node1Dir/config/genesis.json  $dest/config/
      cp $Node1Dir/config/config.toml   $dest/config/
    fi
done


cp -R $DEPLOY $DEST

cat >$PWD/docker-compose.yml << EOF
version: '3.8'

services:
EOF

for i in $(seq 1 $N)
do
cat >>$PWD/docker-compose.yml << EOF
  node$i:
    image:  cmpd/node:latest
    environment:
     - ID=$i
    ports:
    - target: 26656
      published: 26656
      protocol: tcp
      mode: host
    - target: 26657
      published: 26657
      protocol: tcp
      mode: host
    - target: 8545
      published: 8545
      protocol: tcp
      mode: host
    volumes:
    - /home/ubuntu/CMPChain/chain/network/conf/deploy:/cmp
    deploy:
      replicas: 1
      restart_policy:
        condition: on-failure
      placement:
        constraints:
          - node.hostname == node-$i
EOF
done

echo -e "\n------Enjoy it!------\n\n"


total=0

printf "%s\t%s\t\t\t\t\t\t%s\n" "idx" "account" "amount(cmp)"
for i in "${!genesisAccountList[@]}";
do
    printf "%s\t%s\t%s\n" "${i}" "${genesisAccountList[$i]}"  "${accountMapAmount[${genesisAccountList[$i]}]}"
    amount=${accountMapAmount[${genesisAccountList[$i]}]}    
    total=$(echo $total + $amount |bc)
done

demon="cmp"
coin="$total$demon"
echo "total: $coin "


printf "validator ip list: %s \n" "${ipAddrs[@]}" 
printf "chain Id: %s\n" "$chainId"
printf "There are private keys and genesis in directory: %s, please backup the directory.\n" $BACKUP
