### Job Name
#PBS -N gdex-web-service-transform
### Charging account
#PBS -A P43713000
### Request one chunk of resources with 1 CPU and 1GB of memory
#PBS -l select=1:ncpus=1:mem=1GB
### Allow job to run up to 00:05:00
#PBS -l walltime=00:05:00
### Route the job to the gdex queue
#PBS -q gdex
### Join output and error streams into single file
#PBS -j oe

# Environment Management
module --force purge
source /glade/u/home/chiaweih/gdex-web-services/test-gdexws-env/bin/activate


### Parse positional arguments
PAYLOAD="https://boreas.hpc.ucar.edu/gdex-data/services_tmp/payloads/transform.payload.6b7d5b49-fd14-4a69-8a77-281f1ef1efb6.json"

### SETUP .jsonl
jsonl_dir="/glade/campaign/collections/gdex/data/exchange/Web-services/"
output_jsonl="$jsonl_dir/$REQUEST_ID.gdexws.jsonl"

# Clear or create file
> "$output_jsonl"
echo "This is the jsonl with REQUEST_ID:$REQUEST_ID " >> "$output_jsonl"
echo "location of the jsonl file: $output_jsonl" >> "$output_jsonl"

# Shell start message
time_iso=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
echo '{"command": "pbs", "time_of_process": "'$time_iso'", "level": "INFO", "process_message": "PBS job started"}' >> "$output_jsonl"

# Execute transform (the payload can be Boreas link)
transform -p "$PAYLOAD" >> "$output_jsonl"
EXIT_CODE=$?

# Shell end message
time_iso=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
if [ $EXIT_CODE -eq 0 ]; then
    echo '{"command": "pbs", "time_of_process": "'$time_iso'", "level": "INFO", "process_message": "PBS job completed"}' >> "$output_jsonl"
else
    echo '{"command": "pbs", "time_of_process": "'$time_iso'", "level": "ERROR", "process_message": "PBS job failed", "exit_code": '$EXIT_CODE'}' >> "$output_jsonl"
fi
