#!/bin/sh

PROCESS=${1}

shift

OPATTERN_ARRAY=(${1+"$@"})

NPATTERN=''

index=0
count=${#OPATTERN_ARRAY[@]}
while [ $index -lt $count ]; do
    PART="${OPATTERN_ARRAY[$index]}"
    NAPPEND=''
    case "$PART" in
        -o)
            let ++index
            PART="${OPATTERN_ARRAY[$index]}"
            origcoretype=$(echo $PART |sed -ne 's/.*\/core-\?\([^-.]*\)\..*$/\1/p')
            O_OPTION="-o $PART"
            ;;
        -l)
            let ++index
            PART="${OPATTERN_ARRAY[$index]}"
            origcoretype=$(echo $PART |sed -ne 's/.*\/bt-coreinfo-\?\([^-.]*\)\..*$/\1/p')
            L_OPTION="-l $PART"
            ;;
        *)
            NAPPEND=$PART
            ;;
    esac

    if [ "x$NAPPEND" != 'x' ]; then
        if [ "x$NPATTERN" = 'x' ]; then
            NPATTERN="$NAPPEND"
        else
            NPATTERN="$NPATTERN $NAPPEND"
        fi
    fi

    let ++index
done

case "$PROCESS" in
    HWR*|ClockSMain)
        coretype=hwr
        ;;
    CCS*)
        coretype=ccs
        ;;
    rio*)
        coretype=rio
        ;;
    *syslog*)
        coretype=syslog
        ;;
    charon|pluto)
        coretype=ipsec
        ;;
    secfg_test|FPCiTest)
        coretype=fpci
        ;;
esac

if [ "x$coretype" != 'x' ]; then
    if [ "x$O_OPTION" != 'x' ]; then
        O_OPTION=$(echo ${O_OPTION} | sed -e "s#${origcoretype}\.#${coretype}\.#g")
    fi
    if [ "x$L_OPTION" != 'x' ]; then
        L_OPTION=$(echo ${L_OPTION} | sed -e "s#${origcoretype}\.#${coretype}\.#g")
    fi
fi

if [ "x$L_OPTION" != 'x' ]; then
    NPATTERN="$NPATTERN $L_OPTION"
fi
if [ "x$O_OPTION" != 'x' ]; then
    NPATTERN="$NPATTERN $O_OPTION"
fi

eval exec "${NPATTERN}"
