#!/bin/bash

set -euo pipefail

usage="Usage:
  $(basename "$0") [-h] [-m s] [-c n] -- Generate governance prototxt for a given module to be upgraded to a given code id

  where:
      -h  show this help text
      -m  module (bridge, token_bridge, nft_bridge)
      -c  code id (e.g. 4018)"

code_id=""
module=""
while getopts ':hm:c:' option; do
  case "$option" in
    h) echo "$usage"
       exit
       ;;
    m) module=$OPTARG
       ;;
    c) code_id=$OPTARG
       ;;
    :) printf "missing argument for -%s\n" "$OPTARG" >&2
       echo "$usage" >&2
       exit 1
       ;;
   \?) printf "illegal option: -%s\n" "$OPTARG" >&2
       echo "$usage" >&2
       exit 1
       ;;
  esac
done
shift $((OPTIND - 1))

[ -z "$code_id" ] && { echo "$usage" >&2; exit 1; }
[ -z "$module" ] && { echo "$usage" >&2; exit 1; }

address=$(printf "%064x" "$code_id")
TERRA_ID=3
GUARDIAND=guardiand

case "$module" in
  bridge)
    "$GUARDIAND" template contract-upgrade \
      --chain-id $TERRA_ID \
      --new-address "$address" \
      > /tmp/gov.prototxt
    ;;
  token_bridge)
    "$GUARDIAND" template token-bridge-upgrade-contract \
      --chain-id $TERRA_ID --module "TokenBridge" \
      --new-address "$address" \
      > /tmp/gov.prototxt
    ;;
  nft_bridge)
    "$GUARDIAND"  template token-bridge-upgrade-contract \
      --chain-id $TERRA_ID --module "NFTBridge" \
      --new-address "$address" \
      > /tmp/gov.prototxt
    ;;
  *) echo "illegal module $module"
     echo "$usage" >&2
     exit 1
     ;;
esac

cat /tmp/gov.prototxt
"$GUARDIAND" admin governance-vaa-verify /tmp/gov.prototxt >&2
