#!/bin/bash

# This script converts NOAA L1C files in a directory to DBNet-compliant BUFR files using AAPP.

# Get arguments
input_dir=$1

# Switch to input directory
cd $input_dir
 
# Set BUFR environment variables (if not already set)
[ -z "$ORIGINATING_CENTRE" ] && export ORIGINATING_CENTRE=176
[ -z "$SUB_CENTRE" ] && export SUB_CENTRE=22
[ -z "$USE_OB_TIME" ] && export USE_OB_TIME=Y
[ -z "$STATION_NAME" ] && STATION_NAME="mad"

# Create BUFR files
echo eccodes_encodebufr_1c -i amsu*.l1c AMSU-A
eccodes_encodebufr_1c -i amsu*.l1c AMSU-A
echo eccodes_encodebufr_1c -i mhs*.l1c MHS
eccodes_encodebufr_1c -i mhs*.l1c MHS
echo eccodes_encodebufr_1c -i hirs*.l1c HIRS
eccodes_encodebufr_1c -i hirs*.l1c HIRS

# Get satellite name, date, time, orbit from L1C file (e.g., amsual1c_M03_20190521_1522_02779.l1c)
file=$(find . -name \*l1c*.l1c | head -1)
sat_name=$(basename $file | cut -d'_' -f 2)
date=$(basename $file | cut -d'_' -f3)
time=$(basename $file | cut -d'_' -f4)
orbit=$(basename $file | cut -d'_' -f5 | cut -c1-5)

# Set DBNet filename and metadata variables
product_identifier="W_us-noaa-ssec"
station=$STATION_NAME
originator_name="KWBC"
create_time=$(date -u +%Y%m%d%H%M%S)

# Create DBNet AMSU-A BUFR file including GTS headers
sensor_name="amsua"
product_id="INAT"
input_file=(amsual1c*.bufr)
if [ -e "$input_file" ]; then
  output_file=${product_identifier},${sensor_name},DBNet"+"${sat_name}"+"${station}_C_${originator_name}_${create_time}_${sensor_name}_${sat_name}_${date}_${time}_${orbit}_bufr.bin
  echo gtsheaders_bufr.pl $input_file $output_file $product_id $originator_name
  gtsheaders_bufr.pl $input_file $output_file $product_id $originator_name
fi

# Create DBNet MHS BUFR file including GTS headers
sensor_name="mhs"
product_id="INMT"
input_file=(mhsl1c*.bufr)
if [ -e "$input_file" ]; then
  output_file=${product_identifier},${sensor_name},DBNet"+"${sat_name}"+"${station}_C_${originator_name}_${create_time}_${sensor_name}_${sat_name}_${date}_${time}_${orbit}_bufr.bin
  echo gtsheaders_bufr.pl $input_file $output_file $product_id $originator_name
  gtsheaders_bufr.pl $input_file $output_file $product_id $originator_name
fi

# Create DBNet HIRS BUFR file including GTS headers
sensor_name="hirs"
product_id="INHT"
input_file=(hirsl1c*.bufr)
if [ -e "$input_file" ]; then
  output_file=${product_identifier},${sensor_name},DBNet"+"${sat_name}"+"${station}_C_${originator_name}_${create_time}_${sensor_name}_${sat_name}_${date}_${time}_${orbit}_bufr.bin
  echo gtsheaders_bufr.pl $input_file $output_file $product_id $originator_name
  gtsheaders_bufr.pl $input_file $output_file $product_id $originator_name
fi

exit 0
