#!/bin/sh

set -e

DB_NAME=mev_inspect

function get_kube_db_secret(){
    kubectl get secrets mev-inspect-db-credentials -o jsonpath="{.data.$1}" | base64 --decode
}

function db(){
    host=$(get_kube_db_secret "host")
    username=$(get_kube_db_secret "username")
    password=$(get_kube_db_secret "password")

    kubectl run -i --rm --tty postgres-client \
        --env="PGPASSWORD=$password"  \
        --image=jbergknoff/postgresql-client \
        -- $DB_NAME --host=$host --user=$username
}

case "$1" in
  db)
        echo "Connecting to $DB_NAME"
        db
	;;
  listener)
        kubectl exec -ti deploy/mev-inspect -- ./listener $2
	;;
  backfill)
        start_block_number=$2
        end_block_number=$3
        n_workers=$4

        echo "Backfilling from $start_block_number to $end_block_number with $n_workers workers"
        python backfill.py $start_block_number $end_block_number $n_workers
	;;
  inspect)
        block_number=$2
        echo "Inspecting block $block_number"
        kubectl exec -ti deploy/mev-inspect -- poetry run inspect-block $block_number
	;;
  inspect-many)
        start_block_number=$2
        end_block_number=$3
        echo "Inspecting from block $start_block_number to $end_block_number"
        kubectl exec -ti deploy/mev-inspect -- \
            poetry run inspect-many-blocks $start_block_number $end_block_number
	;;
  test)
        echo "Running tests"
        kubectl exec -ti deploy/mev-inspect -- poetry run pytest tests
	;;
  fetch)
      block_number=$2
      echo "Fetching block $block_number"
      kubectl exec -ti deploy/mev-inspect -- poetry run fetch-block $block_number
  ;;
  exec)
        shift
        kubectl exec -ti deploy/mev-inspect -- $@
  ;;
  *)
	echo "Usage: "$1" {db|backfill|inspect|test}"
	exit 1
esac

exit 0
