#!/bin/bash

#This script gets staged files, reads associated parameters and calls API with the given parameters
#If upload is succesful, the files are deleted. Else the files are left in place for the system to try again later
#An additional temp folder was created for testing.
#Remember to comment lines indicating production during testing and vice versa

#folder_path="/home/radio/radio/recordings/temp_success/" #testing
folder_path="/home/radio/radio/recordings/score_test_success/" #production
file_list=$folder_path"*.mp3"
recording_location="kampala" #kampala
source=$(hostname)
freq_files="/home/radio/radio/new_scripts/freq_files/*.txt"
#current_date=$(date +"%Y-%m-%d")
FILE_LIST=$(find $file_list -type f -mmin +10 -printf "%f\n" )

for file in $FILE_LIST
do
	#echo $file
	file_path=$folder_path$file
	#file_name=$(echo $file_path | cut -d/ -f7 )
	radio_freq=$(echo $file | cut -d_ -f1)
	config_id=$(cat $freq_files | grep $radio_freq | cut -d'|' -f3)
	speech=$(cat $file_path".txt" | cut -d, -f1)
	duration=$(cat $file_path".txt" | cut -d, -f2)
	recording_date=$(echo $file | cut -d_ -f2 | cut -dT -f1)

	echo "file_name="$file "location="$recording_location "source="$source "date="$recording_date "speech="$speech "duration="$duration "config_id="$config_id

	##call_radio_api = `curl -X PUT -H 'Content-Type: application/json' -H 'x-api-key: xmd2mIlYZ29LYM24MqmPa8GVMsNkNV9I5F3JdMFX' 'https://yid35l9cbc.execute-api.us-east-1.amazonaws.com/Test/add-audio-file?name=$file_name&location=$recording_location&duration=$duration&date=$current_date&speech=$speech&source=$source'`
	first_endpoint="https://yid35l9cbc.execute-api.us-east-1.amazonaws.com/Prod/add-audio-file?name=$file&location=$recording_location&duration=$duration&date=$recording_date&speech=$speech&source=$source&config_id=$config_id"
	call_radio_api_response=$(curl -X PUT -H 'Content-Type: application/json' -H 'x-api-key: SGfdxvMDNj8zu44zoEAOv3kbacwor8BF37aFVZqj' "${first_endpoint}")
	echo "curl -X PUT -H 'Content-Type: application/json' -H 'x-api-key: xmd2mIlYZ29LYM24MqmPa8GVMsNkNV9I5F3JdMFX' '$first_endpoint'"
	echo "initial_response=>"$call_radio_api_response
	api_body=$(echo $call_radio_api_response | jq -r '.body')
	echo "body=>"$api_body
	echo "curl -X PUT --data-binary '@$file' '$api_body'"
	path="@$file_path"
	call_upload_endpoint=$(curl -X PUT --data-binary "${path}" "${api_body}")
	#curl -X PUT --data-binary '@$file' '$api_body'
	#echo "final_response=>"${call_upload_endpoint}
	curl_output=$?
	echo $curl_output
	if [ $curl_output -eq 0 ] 
	then
		#mv $file_path /home/radio/radio/recordings/temp_mv/ #testing
		rm $file_path #production
		rm $file_path".txt" #production
	fi
	echo ""

done
