#!/bin/sh

## Legacy wrapper for foma

print_usage() {
    echo 'usage: $0 [-utf8|-latin1] [-e "command"] [-f scriptfile] [-h] [-l startscript] [-s binaryfile] [-q] [-v] [-F hfst_format] [-V]'
}

print_help() {
    echo "Imitates xfst using foma and a wrapper script"
    echo
    echo "  -h   print this help"
    echo "  -V   print version info"
    echo "  -F   parameter is HFST3 format name"
    echo
    echo "All other parameters imitate foma/xfst parameters as possible"
}

print_version() {
    echo "hfst-xfst 0.0 (foma 0.9.13)"
    echo "Copyright (c) 2010 University of Helsinki"
    echo "Licence GPLv3: GNU GPL version 3 <http://gnu.org/licenses/gpl.html>"
    echo "This is free software: you are free to change and redistribute it."
    echo "There is NO WARRANTY, to the extent permitted by law."
}

if ! test -t 1 ; then
    extraopts="-p"
fi
while getopts "e:f:hl:s:qvF:u:" flag ; do
    case $flag in
    h) print_help; exit 0;;
    V) print_version; exit 0;;
    v) wrapopts="$wrapopts -v";;
    q) wrapopts="$wrapopts -q";;
    f) ffile="-f $OPTARG";;
    l) lfile="-l $OPTARG";;
    e) extraopts="$extraopts -e \"$OPTARG\"";;
    F) wrapopts="$wrapopts -f $OPTARG";;
    u) utf8=utf8;;
    s) echo "Cannot use XFST automata binaries"; exit 1;;
    ?) echo "Unknown command line switch -$flag$OPTARG, passing on"; extraopts="$extraopts -$flag$OPTARG";;
    esac
done

if test x$utf8 =  xutf8 ; then
    echo "UTF-8 is already default in $0"
fi
if test "x$lfile" = "x-l atin1" ; then
    if test ! -z $ffile ; then
        if type recode ; then
            recode l1..u8 `echo $ffile | sed 's/-f //'`
        else
            echo "missing recode, cannot use latin1"
            exit 1
        fi
    else
        echo "cannot use latin1 in stdin or pipes"
        exit 1
    fi
    lfile=
fi
if test "x$ffile" = "x-f lush" ; then
    ffile=
    extraopts="$extraopts -flush"
fi
if test -t 1 ; then
    if test -z "$ffile" ; then
        echo Running foma without automatic exit at end
        echo Files from interactive session cannot be converted
    fi
    if ! /usr/bin/hfst-foma-wrapper.sh $wrapopts -X"$ffile $efile $lfile $extraopts"; then
        echo "Foma wrapper failed"
        exit 1
    fi
else
    if ! /usr/bin/hfst-foma-wrapper.sh $wrapopts -X"$ffile $efile $lfile $extraopts" > /dev/null; then
        echo "Foma wrapper failed"
        exit 1
    fi
fi
