#! /bin/sh

PATH="`getconf PATH`":"$PATH"
test -z "$COPYEX_DIR" && COPYEX_DIR=/opt/cprocsp/src/rdk/copyex
test -z "$CPP" && CPP="gcc -std=gnu99 -E"
test -z "$AWK" && AWK="gawk"
test -z "$SED" && SED="/bin/sed"
test -z "$CSP_INCLUDE" && CSP_INCLUDE=/opt/cprocsp/include
export PATH COPYEX_DIR CPP AWK SED CSP_INCLUDE

# Arguments: derc.sh <rc_file> <prj_file> <include_dir> <prefix> <out_file_prefix> [<CPP_flags>]

# Assumptions to derc.awk:
# 1. VS_VERSION_INFO goes after all stringtables
# 2. Block names therein are preset and cased.
# 3. There are no commas in CompanyName and LegalCopyright fields (FS-based 
#    parsing)

# CPP is being invoked so because of very smart gcc on fenix, which knows
# about .rc files.

CPPF="-I. -I $4"
for dir in $4/Win32 $4/../Win32/Win32
do
    test -d $dir && CPPF="$CPPF -I $dir"
done
CPPF="$CPPF -D_WIN32 -DRC_INVOKED"
poname=`echo $6|$SED 's%^.*/\([^/]*\)_rc%librdr\1%'`
test -n "$7" && poname=$7

# Change comments beginning after whitespace: "// xxx" to "/* xxx */"
# I use '%' instead of '/', because otherwise there will be a horde of slashes
(
$SED "\%^[ \t]*//%{s%//%/*%;s%/\*.*%& */%;}" "$4/`basename $6`.h" >$6.h && \

rm -f rc_tmp.c && \
(
if test x$2 != x; then # absent file must be represented as ""
    if test -f $2; then
	echo "#include \"$2\"" >> rc_tmp.c
    else
	echo $2 not exists
    fi
fi
) && \

echo "#define AFX_TARG_ENU 1" >> rc_tmp.c && \

(
if test x$1 != x; then
    if test -f $1; then
	echo "#include \"$1\"" >> rc_tmp.c
    else
	echo $1 not exists
    fi
fi
) && \

echo "/* empty auto-generated file */" > ./afxres.h && \

(
    cat <<eof_prefix
#include "$3"
#if !defined _RESOURCE
eof_prefix

$CPP -I$CSP_INCLUDE/reader.kit \
    -I$CSP_INCLUDE $CPPF $8 rc_tmp.c 2>err.out 1>cpp.out
cat cpp.out|(LANG=ru_RU.cp1251 LC_ALL=ru_RU.cp1251 $AWK -f $COPYEX_DIR/derc.awk prefix="$5" catname="$poname")| \
$SED -e 's/\"\"/\\\"/g' 
) > $6.c || \
test -s err.out && \
cat cpp.out|(LANG=ru_RU.cp1251 LC_ALL=ru_RU.cp1251 $AWK -f $COPYEX_DIR/derc.awk po=en) > ${poname}.msg && \
cat cpp.out|(LANG=ru_RU.cp1251 LC_ALL=ru_RU.cp1251 $AWK -f $COPYEX_DIR/derc.awk po=ru) > ${poname}_cp1251.msg && \
$COPYEX_DIR/localize_dist.sh $poname
) || exit $?
