#!/bin/bash

# Display options to the user
echo "Select an option:"
echo "1. Create New Wallet"
echo "2. Import Old Wallet"
echo "3. To Continue (Skip if you already have a wallet)"

# Get user input
read OPTION

case $OPTION in
    1)
        echo "Please enter your wallet name:"
        read WALLET
        echo "Creating a new wallet..."
        initiad keys add $WALLET
        echo "Please Backup the Mnemonic keys above."
        echo ""  # Adds a blank line for better spacing
        ;;
    2)
        echo "Please enter your wallet name:"
        read WALLET
        echo "Importing an old wallet..."
        initiad keys add $WALLET --recover
        echo "Please Backup the Mnemonic keys above."
        echo ""  # Adds a blank line for better spacing
        ;;
    3)
        echo "Skipping wallet setup..."
        ;;
    *)
        echo "Invalid option, exiting..."
        exit 1
        ;;
esac

# Update or add WALLET to bash profile
if [[ -n "$WALLET" ]]; then
    if grep -q 'export WALLET=' ~/.bash_profile; then
        # WALLET exists, replace it
        sed -i "/export WALLET=/c\export WALLET=$WALLET" ~/.bash_profile
    else
        # WALLET does not exist, add it
        echo "export WALLET=$WALLET" >> ~/.bash_profile
    fi
    source ~/.bash_profile
    echo "Wallet name stored and bash profile updated."
fi

echo "Use this link to access the faucet and get funds: https://faucet.testnet.initia.xyz/"
echo ""  # Adds a blank line for better spacing

while true; do
    echo "Press 1 to check your balance:"
    echo "Press 2 to create a validator (Note: You can only create a validator if you have a balance):"
    read CHOICE

    case $CHOICE in
        1)
            echo "Checking balance for $WALLET..."
            initiad q bank balances $WALLET
            ;;
        2)
            echo "Please enter your validator name:"
            read VAL_MONIKER
            echo "Creating a validator..."
            initiad tx mstaking create-validator \
              --amount=500000uinit \
              --pubkey=$(initiad tendermint show-validator) \
              --moniker=$VAL_MONIKER \
              --chain-id=initiation-1 \
              --commission-rate=0.05 \
              --commission-max-rate=0.10 \
              --commission-max-change-rate=0.01 \
              --from=$WALLET \
              --identity="" \
              --website="" \
              --details="BlackNodes Tutorial" \
              --gas=2000000 --fees=300000uinit \
              --node https://initia-testnet-rpc.blacknodes.net:443 \
              -y
            echo "export VAL_MONIKER=$VAL_MONIKER" >> ~/.bash_profile
            source ~/.bash_profile
            break
            ;;
        *)
            echo "Invalid option, please try again."
            ;;
    esac
done
