#!/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

	case $platform in
	    # Replace EN-DASH (UTF-8 encoding) at line start with -
	    Linux) LC_ALL=C sed -i $'s/^\u2013/-/g' "${1%.docx}.txt" ;;
	    
	    # Replace EN-DASH (Windows-1252 encoding) at line start with -
	    # Remove CR (0x0d) put by libreoffice in windows before each LF (0x0a)
	    CYGWIN*) LC_ALL=C sed -i $'s/^\x96/-/g; s/\r$//' "${1%.docx}.txt" ;;
	    *) echo "Unkown platform $platform"
	       exit 1;;
	esac

	# Changes things that should not be so in the specification
	# Change "-- Cond N3C MP" to "-- Cond N3C-MP" (to respect condition naming rules)
	LC_ALL=C sed -i 's/-- Cond N3C MP/-- Cond N3C-MP/' "${1%.docx}.txt"
	LC_ALL=C sed -i 's/^N3C MP/N3C-MP/' "${1%.docx}.txt"
	LC_ALL=C sed -i 's/-- Cond HOAndServCellAdd,$/-- Cond HOAndServCellAdd/' "${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

