#!/bin/bash

if [[ $# -eq 0 ]] ; then
    echo "Usage: ${0##*/} file [files]"
    echo "Extract ASN.1 from one or more 3GPP 38.331 docx files and save then to .asn files"
    exit 1
fi

if [[ ! -w . ]] ; then
    echo "Cannot write to current directory"
    exit 1
fi

platform=$(uname)

case $platform in
    Linux) libreoffice="libreoffice" ;;
    CYGWIN*) libreoffice="soffice" ;;
    *) echo "Unkown platform $platform"
       exit 1;;
esac

if [[ ! -x $(which "$libreoffice") ]] ; then
    echo "Cannot find libreoffice executable"
    echo "Make sure it is installed and the PATH variable includes its path"
    exit 1
fi
   
while [ "$#" -gt 0 ]; do

    echo "Processing $1"

    if [[ ! -f "$1" ]] || [[ ! -r "$1" ]] ; then
	echo "$1 is not a readable file"
	shift
	continue
    fi    

    if [[ -e "${1%.docx}.txt" ]] ; then
	echo "${1%.docx}.txt already exists: skipping conversion"
	
    else
	$libreoffice --convert-to txt "$1"

	if [[ ! -f "${1%.docx}.txt" ]] || [[ ! -r "${1%.docx}.txt" ]] ; then
	    echo "libreoffice did not create ${1%.docx}.txt"
	    shift
	    continue
	fi

	# On windows, soffice adds CR characters at line ends and produces EN-DASH in Windows-1252 enconding, i.e. 0x96
	# Remove the CR at each line end and convert EN-DASH to normal minus
	echo "${1%.docx}.txt"
	LC_ALL=C sed -i $'s/\x96/-/g' "${1%.docx}.txt"
	LC_ALL=C sed -i $'s/\r$//' "${1%.docx}.txt"

    fi

    if [[ -e "${1%.docx}.asn" ]] ; then
	echo "${1%.docx}.asn already exists: not regenerated"
	shift
	continue
    fi

       
    cat "${1%.docx}.txt" | awk '/^-- ASN1START$/,/^-- ASN1STOP$/' | grep -Evxe '-- ASN1ST(ART|OP)' | grep -v '^--' | awk 'NF || p; { p = NF }' p=0 > "${1%.docx}.asn"

    if [[ -e "${1%.docx}.asn" ]] ; then
	echo "${1%.docx}.asn was generated"
    fi
    shift
done

