#!/bin/bash
#
# Create WIS2 notification message for DBNet
#
# Reference: https://wmo-im.github.io/wis2-notification-message/standard/wis2-notification-message-DRAFT.pdf
#
# 27/03/2024 Initial draft. Nigel Atkinson
# 24/04/2024 Incorporate feedback from EUMETSAT and SSEC/UW/CIMSS
# 28/07/2026 Update following recommendations of DBNet-CG Intersessional Meeting 12 May 2026
#
###########################################################################################################

infile=$1    #e.g. W_us-noaa-ssec,iasi,DBNet+metopb+gua_C_KWBC_20240320120049_iasi_M01_20240320_1136_59694_bufr.bin
centre=$2    #e.g. us-cimss, to be used in the "data_id". Country and centre.
url=$3       #e.g. https://opendata.dwd.de/test/wis2/cache/24h/us-cimss/

[ $# == 3 ] || { echo "Usage: $0 infile centre url"; exit 1; }

[ -f $infile ] || { echo "Error: input file does not exist"; exit 1; }

filebase=$(basename $infile)

typeset -l instr
typeset -l sat
instr_in=$(echo $filebase | cut -d"," -f2)
sat_in=$(echo $filebase | cut -d"+" -f2)

#Date/time of metadata creation

now=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)

#Extract the AAPP time stamp YYYYmmdd. It must start with "2" and have 8 digits. HHMMSS or HHMM comes next.

set $(IFS="_"; echo $filebase)
while [ $1 ] && [[ ${1:0:1} != 2 || ${#1} != 8 ]]; do
  shift
done
if [ "$1" ] && [ "$2" ]; then
  SS=${2:4:2}
  SS=${SS:-00}
  datetime=$(date -u +%Y-%m-%dT%H:%M:%SZ -d "$1 ${2:0:2}:${2:2:2}:$SS")
else
  datetime=$now      #in case AAPP time stamp can't be found in the file name
fi

#Make the satellite and instrument names conform to the WMO list of Topics

case $sat_in in
  metopb ) sat=metop-b ;;
  metopc ) sat=metop-c ;;
  metop01) sat=metop-b ;;
  metop03) sat=metop-c ;;
  npp    ) sat=snpp    ;;
  noaa18 ) sat=noaa-18 ;;
  noaa19 ) sat=noaa-19 ;;
  noaa20 ) sat=noaa-20 ;;
  noaa21 ) sat=noaa-21 ;;
  noaa22 ) sat=noaa-22 ;;
  noaa23 ) sat=noaa-23 ;;
       * ) sat=$sat_in ;;
esac
case $instr_in in
  amsua) instr=amsu-a ;;
      *) instr=$instr_in ;;
esac

uuid=$(uuidgen -t) || { echo "Error generating uuid"; exit 1; }

sha512string=$(sha512sum $infile | cut -f1 -d\ | xxd -r -p | base64 -w 0)    #sha512 in base64 format
if [ $? != 0 ]; then
  echo "Error computing sha512 string"
  exit 1
fi

bytes=$(stat -c %s $infile)

cat <<EOF
{
  "id": "${uuid}",
  "type": "Feature",
  "conformsTo": "http://wis.wmo.int/spec/wnm/1/conf/core",
  "geometry": null,
  "properties": {
    "pubtime": "${now}",
    "data_id": "${filebase}",
    "datetime": "${datetime}",
    "dataDomain": "DBNet",
    "integrity": {
      "method": "sha512",
      "value": "${sha512string}"
    }
  },
  "links": [
    {
      "href": "${url}${filebase}",
      "rel": "canonical",
      "type": "application/bufr",
      "length": $bytes
    }
  ]
}
EOF
