#!/bin/bash
#

function usage {
    echo
    echo "Usage: $0 <connection URL>"
    echo
    echo "Example: $0 'http://10.1.2.3:9047'"
    echo
    exit
}

function check_creds {
    if [ $DREMIO_USER"x" = "x" ] || [ $DREMIO_PASS"x" = "x" ]
    then
        echo "Please ensure DREMIO_USER and DREMIO_PASS are both set"
    fi
}

function login {
    RESP=$(curl -s -H "Content-Type: application/json" -X POST "$TARGET/apiv2/login" \
        -d '{
             "userName":"'$DREMIO_USER'", 
             "password":"'$DREMIO_PASS'"
        }' \
       )
    TOKEN=$(echo $RESP | jq -r '.token')
}

# Runs an SQL query to find all the views. Run the query, get the job ID and then parse the results out to json
function run_sql {
   # Run SQL job
   SQL_REQ=$(curl -s -H 'Content-Type: application/json' -H "Authorization: _dremio$TOKEN" -X POST "$TARGET/api/v3/sql" \
      -d '{"sql": "'"$SQL_QUERY"'"}')
   # Find SQL job ID
   SQL_ID=$(echo $SQL_REQ | jq -r '.id')
   # Delay to allow SQL to run (its not instant!)
   sleep $DELAY
   # Use id to find job results (pulls the paths from the VDS we setup)
   curl -s -H 'Content-Type: application/json' -H "Authorization: _dremio$TOKEN" -X GET "$TARGET/api/v3/job/$SQL_ID/results" | jq . > $VIEWS_FILE
   # Populate the paths into a file
   jq '.rows[]."EXPR$0"' $VIEWS_FILE > $DS_PATH_FILE
}


function compile_sql {
   cat /dev/null > $REFRESH_FILE
   while read DS_PATH
   do
      DS_PATH_ENC=$( echo $DS_PATH | sed -E "s/\ /%20/g" )
      echo -e "ALTER PDS $DS_PATH_ENC FORGET METADATA" | sed -E "s/\./\"\.\"/g" >> $REFRESH_FILE
      echo -e "ALTER PDS $DS_PATH_ENC REFRESH METADATA" | sed -E "s/\./\"\.\"/g" >> $REFRESH_FILE
   done < $DS_PATH_FILE
}

# Check args
if [ $# -ne 1 ]; then
    usage
fi

# Setup
RESP=""
TOKEN=""
CATALOG=""
SQL_QUERY="select * from Shared.pds"
SQL_RESULT=""
CATALOG_FILE=".catalog_info"
VIEWS_FILE=".views_info"
DS_PATH_FILE=".dspath_info"
REFRESH_FILE="refresh_info.out"
TARGET=$1
DELAY=5

# Run
check_creds
login
run_sql
compile_sql
echo "Output in $REFRESH_FILE"
