#!/bin/bash

echo TASTE Data View Convertor - From ASN.1 to AADLV2

# User may pass several ASN.1 files as parameters
for f in $@
do
    # Ignore taste internal ASN.1 files
    name=$(basename "$f")
    if [ "$name" != taste-types.asn -a "$name" != __ExtraTypes.asn ]
    then
        if [ ! -f "$f" ]
        then
            echo File not found: $f
            exit 1
        else
            echo Using file: $f
            filename=$(readlink -e "$f")
            DATAVIEW+="$filename "
            acnfile=$(readlink -e "${f%.*}.acn")
            if [ -f "$acnfile" ]
            then
                echo Using ACN file: $acnfile
                DATAVIEW+="$acnfile "
            fi
        fi
    fi
done

# If DATAVIEW string is empty, check for DataView.asn in current folder
if [ -z "$(echo -n $DATAVIEW)" ]
then
    if [ -f DataView.asn ]
    then
        echo 'Using file: DataView.asn'
        DATAVIEW=$(readlink -e DataView.asn)
    else
        echo Error: no data view found
        echo 'Usage: taste-update-data-view <set of ASN.1 files>'
        exit 1
    fi
    if [ -f DataView.acn ]
    then
        echo 'Using file: DataView.acn'
        DATAVIEW+=" $(readlink -e DataView.acn)"
    fi
fi

#AADL=${DATAVIEW%.*}.aadl
AADL=DataView.aadl

if [ -f __ExtraTypes.asn ]
then
    echo 'Using file: __ExtraTypes.asn'
    DATAVIEW+=" $(readlink -e "__ExtraTypes.asn")"
fi

if [ -f __ExtraTypes.acn ]
then
    echo 'Using file: __ExtraTypes.acn'
    DATAVIEW+=" $(readlink -e "__ExtraTypes.acn")"
fi

DATAVIEW+=" $(taste-config --prefix)/share/taste-types/taste-types.asn"

asn2aadlPlus $DATAVIEW "$AADL" -aadlv2

if [ "$?" = "1" ]
then
    echo 'ERROR: Impossible to convert the dataview from ASN.1 to AADL' > /dev/stderr
    exit 1
else
    echo All OK
    exit 0
fi

