#!/bin/bash

scriptDir="`dirname \"$0\"`" # Where we are physically
workDir="`pwd`" # Where we run from
pod=$1 # This instance hostname (pod)
buildId=$2 # Build GUID
dataSourceTitle=$3 # Data source display name
cubePhysicalName=$4 # Cube physical name
originator=$5 # One of: REST/NextECM/Scheduler/CLI
buildIntentType=$6 # One of: NEW/EXISTS
tempPath=$7 # The default temp path for build plugins
tmpEcmModelFile=$8 # ECM model path (only in prebuild)
tmpQueriesFile=$9 # Queries index path (only in postbuild)

. "$scriptDir/../plugin_utils.sh"
. "$scriptDir/../sisense.sh"
log_input
log_info "Starting at $workDir"

# Parameters:
################################################################################

# Tables' titles list - leave empty to export all tables, or define specific:
# ("Table 1" "Table 2" ...)
declare -a tables=()

# Fail if table query not found
failIfNoQuery=false

# Export target path
exportTarget="$scriptDir/export"

# Implementation:
################################################################################

# Errors
noTarget=101
noQueryFound=102
saveQueryFailed=103
mClientFailed=104
csvNotSaved=105

# Validate target
mkdir -p "$exportTarget"
if [ ! -d "$exportTarget" ]; then
	log_error "\"$exportTarget\" wasn't created or is not a directory."
	exit $noTarget
fi

# If tables is empty, get all available tables
if [ ${#tables[@]} -eq 0 ]; then
	parse_json_keys $tmpQueriesFile
	tables=("${jsonKeys[@]}")
fi
log_info "Exporting ${#tables[@]} tables"

# Handle each table
queries=$(<$tmpQueriesFile)
for table in "${tables[@]}"; do
	log_info "Exporting table: $table"
	
	# Extract the query
	query_path=".[\"$table\"]"
	query=$(parse_json_field "$queries" "$query_path")
	log_debug "query=$query"
	if [ -z "$query" ] || [ "null" == "$query" ]; then
		log_error "The table \"$table\" has no query defined."
		if $failIfNoQuery; then
			exit $noQueryFound
		else
			continue
		fi
	fi
	
	# Save the query
	clean_table=$(simplify_name "$table")
	query_file=$(temp_filename "${clean_table}_query.sql")
	echo "${query};" >> "$query_file"
	validate_last_call "Failed to save query file $query_file." $saveQueryFailed
	
	# Export to CSV
	log_info "Exporting results of $query_file"
	csv_file="${exportTarget}/${clean_table}.csv"
	if [ -f "$csv_file" ]; then
		log_info "$csv_file already exists, size=`stat -c %s \"$csv_file\"`, overriding"
	fi
	./mclient -lsql "$query_file" -EUTF-8 -fcsv > "$csv_file"
	validate_last_call "MClient runtime returned $?." $mClientFailed
	if [ ! -f "$csv_file" ]; then
		log_error "Failed to save CSV of $table."
		exit $csvNotSaved
	fi
	log_info "\"$table\" export: Saved $csv_file, size=`stat -c %s \"$csv_file\"`"
done

################################################################################

# If we get here, exit value will be 0
log_info "Done"
