#!/bin/sh -e
# ----------------------------------------------------
# This script uses the Open Source asn1c to check all used ASN.1 modules
# are compile clean (no guarantee the generated code is valid).
#
# The used compile binary was built from here:
#   https://github.com/brchiu/asn1c/commits/velichkov_s1ap_plus_option_group_plus_adding_trailing_ull
#
# The referenced ISO ASN.1 modules are pulled from the ISO Standards Maintenance Portal
# Yet not all are compile clean, thus minor fixed need to be done.
# All these changes are irrelevant for the resulting encoding.
#  - Fixing duplicate DE tags
#  - Fixing OID typo
#  - Removing unused types (which bloat the IMPORTS)
# ----------------------------------------------------

#set -x
ASN_CACHE=".external"
ASN_OUT=".build"

mkdir -p ${ASN_CACHE} ${ASN_OUT}

ASN1_COMMON="cdd/ETSI-ITS-CDD.asn DSRC.asn DSRC-addgrp-C.asn DSRC-region.asn"
ASN1C_OPTIONS="-E -F -fcompound-names -fknown-extern-type=DATE"

python3 asn2md/asnimports.py --verbose -o ${ASN_CACHE} IVIM-PDU-Descriptions.asn ${ASN1_COMMON} > ${ASN_CACHE}/dsrc-ext-modules
ASN1_IMPORT=$(cat ${ASN_CACHE}/dsrc-ext-modules)

asn1c ${ASN1C_OPTIONS} -pdu=SPATEM SPATEM-PDU-Descriptions.asn ${ASN1_COMMON} > ${ASN_OUT}/SPATEM.asn 2> ${ASN_OUT}/SPATEM.err

asn1c ${ASN1C_OPTIONS} -pdu=MAPEM MAPEM-PDU-Descriptions.asn ${ASN1_COMMON} > ${ASN_OUT}/MAPEM.asn 2> ${ASN_OUT}/MAPEM.err

asn1c ${ASN1C_OPTIONS} -pdu=SREM SREM-PDU-Descriptions.asn ${ASN1_COMMON} > ${ASN_OUT}/SREM.asn 2> ${ASN_OUT}/SREM.err

asn1c ${ASN1C_OPTIONS} -pdu=SSEM SSEM-PDU-Descriptions.asn ${ASN1_COMMON} > ${ASN_OUT}/SSEM.asn 2> ${ASN_OUT}/SSEM.err

asn1c ${ASN1C_OPTIONS} -pdu=RTCMEM RTCMEM-PDU-Descriptions.asn ${ASN1_COMMON} > ${ASN_OUT}/RTCMEM.asn  2> ${ASN_OUT}/RTCMEM.err

asn1c ${ASN1C_OPTIONS} -pdu=IVIM IVIM-PDU-Descriptions.asn ${ASN1_IMPORT} ${ASN1_COMMON} > ${ASN_OUT}/IVIM.asn 2> ${ASN_OUT}/IVIM.err

python3 asn2raw.py DSRC.asn > ${ASN_OUT}/DSRC.raw.asn
python3 asn2raw.py DSRC-region.asn > ${ASN_OUT}/DSRC-region.raw.asn
python3 asn2raw.py DSRC-addgrp-C.asn > ${ASN_OUT}/DSRC-addgrp-C.raw.asn

echo "++++++++++++++++++++++++"
echo "+++ SUCCESS"
echo "+++ All modules compiled"
sha256sum *.asn
echo "++++++++++++++++++++++++"
