apiVersion: v1
kind: ConfigMap
metadata:
  name: validator
data:
  validator-setup.sh: |
    # Wait for port to be available via 
    while [ -z "$NAT_EXTERNAL_PORT" ]; do
      echo "Searching for port...";
      port=$(cat /etc/podinfo/annotations | grep "k8s/2154" | grep -oE "\"[0-9]+\"" | grep -oE "[0-9]+" | xargs);
      if [ -n "$port" ]; then
        export NAT_EXTERNAL_IP=$(wget -qO- ifconfig.me);
        export NAT_EXTERNAL_PORT=$port;
        echo "Port found! NAT_EXTERNAL_IP=$NAT_EXTERNAL_IP NAT_EXTERNAL_PORT=$NAT_EXTERNAL_PORT";
        echo "export NAT_EXTERNAL_IP=$NAT_EXTERNAL_IP" >> ~/.profile;
        echo "export NAT_EXTERNAL_PORT=$NAT_EXTERNAL_PORT" >> ~/.profile;
        break;
      fi;
      sleep 2;
    done;

    echo "Starting miner...";
    /opt/miner/bin/miner daemon;
    touch /tmp/miner-started;

    echo "Starting stats loop...";
    v="/opt/miner/bin/miner";
    dir="/var/data/stats";
    mkdir -p $dir;

    # Dump stats every 120s
    while true; do
      miner_name="$($v info name)";
      match="$(echo "$miner_name" | grep -E '^[a-z]+\-[a-z]+\-[a-z]+')";
      if [ -n "$match" ]; then
        echo "[Stats] Dumping stats to $dir ...";
        start_time="$(date -u +%s)";
        echo "$miner_name" > $dir/info_name;
        $v info height > $dir/info_height;
        $v info p2p_status > $dir/info_p2p_status;
        $v info in_consensus > $dir/info_in_consensus;
        $v info block_age > $dir/info_block_age;

        $v hbbft perf --format csv > $dir/hbbft_perf.csv;
        $v peer book -s --format csv > $dir/peer_book.csv;
        $v ledger validators --format csv > $dir/ledger_validators.csv;
        $v print_keys > $dir/print_keys;
        $v versions > $dir/versions;
        end_time="$(date -u +%s)";
        elapsed="$(($end_time-$start_time))";
        echo "[Stats] Stats dump took $elapsed seconds";

        sleep 120;
      else
        echo "[Stats] Can't dump stats. Validator hasnt started yet '$miner_name'";
        sleep 5;
      fi;
    done &

    # Version check every 15 minutes
    while [[ $VALIDATOR_VERSION == "latest" ]]; do
      # Install jq to make our lives easier
      if [ -z "$(which jq)" ]; then
        echo "[Version] Installing jq dependency";
        wget https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 --output-document="/usr/bin/jq";
        chmod +x /usr/bin/jq;
      fi;

      in_consensus="$($v info in_consensus)";
      if [[ $in_consensus == "true" ]]; then
        echo "[Version] Validator currently in consensus. Skipping version check.";
        sleep 900;
        continue;
      fi;

      container_version="$(miner versions | grep -oE "\d+\.\d+\.\d+")";
      if [ -z "$container_version" ]; then
        echo "[Version] Couldn't fetch version";
        sleep 30;
        continue;
      fi;

      echo "[Version] Checking if validator needs to be updated ($container_version)";
      QUAY_URL="https://quay.io/api/v1/repository/team-helium/validator/tag/?limit=10&page=1&onlyActiveTags=true";
      ARCH=amd;
      quay_response=$(wget -qO- "$QUAY_URL");

      if [ -z "$quay_response" ]; then
        echo "[Version] Bad response from quay.io $quay_response";
        sleep 30;
      else
        current_version_sha=$(echo "$quay_response" | jq -r -c --arg ARCH "$ARCH" --arg VER "$container_version" '[ .tags[] | select( .name | contains($ARCH) and contains($VER)) ][0].manifest_digest');
        current_version_name=$(echo "$quay_response" | jq -r -c --arg ARCH "$ARCH" --arg VER "$container_version" '[ .tags[] | select( .name | contains($ARCH) and contains($VER)) ][0].name');

        IMAGE_NAME_SEARCH="latest-validator-";
        if [[ "$current_version_name" == *"testnet_val"* ]]; then
          IMAGE_NAME_SEARCH="testnet_val";
        fi;

        latest_version_sha=$(echo "$quay_response" | jq -r -c --arg ARCH "$ARCH" --arg NAME "$IMAGE_NAME_SEARCH" '[ .tags[] | select( .name | contains($ARCH) and contains($NAME)) ][0].manifest_digest');

        if [[ "$current_version_sha" == "$latest_version_sha" ]]; then
          echo "[Version] Already at latest version $current_version_sha ($container_version)";
        else
          echo "[Version] Out of date!";
          echo "[Version] Latest $latest_version_sha";
          echo "[Version] Current $current_version_sha ($container_version)";
          echo "[Version] Shutting down validator";
          
          tail_process=$(pgrep -f "tail -F /var/data");
          kill "$tail_process";
          exit 1;
        fi;
        sleep 1800;
      fi;
    done &

    echo "Tailing validator logs...";
    tail -F /var/data/log/*.log;
    # Leave line break at end
