#!/bin/sh
#
# Due to the fact that the long data type in Tru64 UNIX is 64-bit
# whereas most of the OpenOffice source code make the assumption that
# long is 32-bit. Thus to prevent potential problem, the script is
# used to map the long data type in .h, .hxx & .cxx files to int
# which is 32-bit long.
#
# Usage: redefine_long [-r|-d]

Initialize()
{
    DEFINE_LONG="\
#if defined(TRU64) && !defined(long)
#define	long	int
#endif"

    UNDEF_LONG="\
#if defined(TRU64) && defined(long)
#undef long
#endif"

    EXCLUDE_LISTS="./dmake ./moz ./solver ./solenv ./tools ./sal\
    ./psprint ./bridges ./freetype ./berkeleydb ./external\
    ./dtrans/source/X11 ./stlport \
    ./vcl/unx/source/window/FWS.cxx ./vcl/unx/source/app/wmadaptor.cxx\
    ./svtools/inc/sbxvar.hxx ./sc/source/filter/inc/XclImpStream.hxx"
    DEXCLUDE_LISTS="/jpeg/d;/mcvmath/d;/\/$GVERDIR\//d"
    INCLUDE_LISTS="./tools/inc/link.hxx ./tools/inc/gen.hxx"
    RESTORE=
    DIFF=
    SOLENVBIN=$SOLARENV/$OUTPATH/bin
    INSREDEF=$SOLENVBIN/ins_redefine

    [ $# -ge 1 -a "$1" = "-r" ] && RESTORE=1
    [ $# -ge 1 -a "$1" = "-d" ] && DIFF=1

    [ -z "$SRC_ROOT" ] && {
	echo "SRC_ROOT environment variable not found!"
	exit 1
    }
    cd $SRC_ROOT
}

Redefine_Long()
{
    #
    # Create ins_redefine, if necessary
    #
    [ -x $INSREDEF ] || Generate_ins_redefine

    #
    # Process .h & .hxx files
    #
    RMEXCLUDE=`echo $EXCLUDE_LISTS | fmt -1 | sed -e "s#/#\\\\\\\\/#g;s#^#-e /^#;s#\\$#/d#"`
    LOGFILE=/tmp/.log_$$
    (find . \( -name "*.h" -o -name "*.hxx" -o -name "*.c" -o -name "*.cxx" -o -name "*.imp" \) |\
    sed $RMEXCLUDE -e $DEXCLUDE_LISTS; echo $INCLUDE_LISTS | fmt -1) |\
    (CNT=0; while read file
    do
	$INSREDEF "$DEFINE_LONG" "$UNDEF_LONG" $file > $LOGFILE
	[ $? -eq 0 ] && {
	    echo File $file patched.
	    CNT=`expr $CNT + 1`
	    [ -s $LOGFILE ] && cat $LOGFILE
	    [ -n "$DIFF"  ] && diff -c $file.orig $file
	}
    done
    rm -f $LOGFILE
    echo "$CNT files patched.")
}

Restore_Long()
{
    find . -name "*.orig" | sed -e $DEXCLUDE_LISTS | (CNT=0; while read orgfile
    do
	file=`echo $orgfile | sed -e 's/.orig$//'`
	[ -f $orgfile -a -f $file ] && {
	    mv -f $orgfile $file
	    echo "File $file restored."
	    CNT=`expr $CNT + 1`
	}
    done
    echo "$CNT files restored.")
}

Generate_ins_redefine()
{
    cat > $SOLENVBIN/ins_redefine.c << EOF
/*
 * This program insert the long redefinition macros into source files
 * that have embedded "#include" directives at the appropriate locations.
 *
 * Usage: ins_redefine <define_macro> <undef_macro> <file> 
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define	MACRO_MAX	64
#define	DEFMACRO(i)	i
#define	UNDMACRO(i)	((i) | 0x80000000)
#define	GETOFFSET(o)	((o) & 0x7fffffff)
#define	ISDEFMACRO(i)	(!((i) & 0x80000000))
#define	ISUNDMACRO(i)	((i) & 0x80000000)

static char usage[] = "%s <define_macro> <undef_macro> <file>\n" ;
static int  mac_offset[MACRO_MAX] ;
static int  mac_idx		  ;


main(int argc, char **argv)
{
    char *define_macro	  ;
    char *undef_macro	  ;
    char *filename	  ;
    char *buffer	  ;
    char  line [BUFSIZ]	  ;
    char  nfile[PATH_MAX] ;
    char  ofile[PATH_MAX] ;
    int   bufuse, bufmax  ;
    int	  dmlen, umlen    ;
    int	  hascomma	  ;
    int   previnc	  ;
    int	  haslong	  ;
    int	  incomment	  ;
    int	  idx, wrtoff	  ;
    int	  linenum	  ;
    int	  iflevel	  ;
    int   inclevel	  ;
    int   ifline	  ;
    int   ifoffset	  ;
    int	  upifoff	  ;
    FILE *infile	  ;
    FILE *outfile	  ;

    if (argc != 4)
    {
	fprintf(stderr, usage, argv[0]) ;
	exit(1) ;
    }
    define_macro = argv[1] ;
    undef_macro  = argv[2] ;
    filename     = argv[3] ;

    /*
     * Temp output file = <file>.new
     */
    strcpy(nfile, filename) ;
    strcat(nfile, ".new"  ) ;

    /*
     * Original file = <file.orig>
     */
    strcpy(ofile, filename) ;
    strcat(ofile, ".orig" ) ;

    /*
     * Open input file
     */
    if ((infile = fopen(filename, "r")) == NULL)
    {
	fprintf(stderr, "Source file %s not found!\n", filename) ;
	exit(1) ;
    }

    buffer = malloc(BUFSIZ) ;
    bufuse = 0	    ;
    bufmax = BUFSIZ ;
    dmlen  = strlen(define_macro) ;
    umlen  = strlen(undef_macro ) ;

    /*
     * Process line-by-line
     * Insert a long redefinition macro at the end of the last #include
     * before ; is found. Then a undef and redefinition macro will be added
     * before and after each #include directive.
     */
    hascomma  = 0 ;
    haslong   = 0 ;
    previnc   = 0 ;
    incomment = 0 ;
    linenum   = 0 ;
    iflevel   = 0 ;
    inclevel  = 0 ;
    ifline    = 0 ;
    ifoffset  = 0 ;
    upifoff   = 0 ;
    while (fgets(line, sizeof(line), infile) != NULL)
    {
	int   len  = strlen(line) ;
	char *cptr = line ;

	linenum++ ;
	if (bufuse + len >= bufmax)
	{
	    bufmax += BUFSIZ ;
	    buffer = realloc(buffer, bufmax) ;
	}
	strcpy(buffer + bufuse, line) ;
	bufuse += len ;
	while (isspace(*cptr)) cptr++ ;	/* Skip leading space */
	if (*cptr == '\n')
	{
	    if (ifline == linenum - 1)
		ifline++ ;
	    continue ;	/* Skip empty line */
	}
	if (incomment)
	{
	    if ((cptr = strstr(line, "*/")) != NULL)
		incomment = 0 ;
	}
	else if (*cptr == '#')
	{
	    int isdefine = 0 ;
	    cptr++;
	    while (isspace(*cptr)) cptr++ ;
	    /*
	     * Look for #include, but not the yyrscyacc.cxx file
	     */
	    if ((strncmp("include", cptr, 7) == 0) && (strstr(cptr, "yyrscyacc.cxx") == NULL))
	    {
		if (hascomma)
		{
		    if (mac_idx >= MACRO_MAX - 1)
		    {
			fprintf(stderr, "Too many independent #include directives in source files %s!\n",
				filename) ;
			exit(1) ;
		    }
		    else if (mac_idx == 0)
			mac_offset[mac_idx++] = DEFMACRO(0) ;
		    if (previnc)
		    {
			/* Move the redefine macro down one #include line */
			if (iflevel == inclevel)
			     mac_offset[mac_idx-1] = DEFMACRO(bufuse) ;
		    }
		    else
		    {
			/*
			 * Record the offset to previous #if, if available.
			 */
			upifoff = (ifline == linenum - 1) ? (bufuse - len - ifoffset) : 0 ;
			mac_offset[mac_idx++] = UNDMACRO(bufuse - len) ;
			mac_offset[mac_idx++] = DEFMACRO(bufuse) ;
			inclevel 	      = iflevel		 ;
		    }
		}
		else if (!mac_idx || (iflevel <= inclevel))
		{
		    mac_offset[0] = DEFMACRO(bufuse) ;
		    mac_idx	  = 1		     ;
		    inclevel      = iflevel	     ;
		}
		previnc = 1 ;
		continue    ;
	    }
	    else if (strncmp(cptr, "endif", 5) == 0)
	    {
		iflevel-- ;
	        if (previnc)
		{
		    if (hascomma && upifoff && (iflevel == inclevel - 1))
		    {
			mac_offset[mac_idx-2] -= upifoff ;
			upifoff		       = 0	 ;
			inclevel  	       = iflevel ;
		    }
		    if (hascomma && (iflevel == inclevel))
			mac_offset[mac_idx-1] = DEFMACRO(bufuse) ;
		    else if (hascomma && (iflevel < inclevel))
			previnc = 0 ;
		    else if (!hascomma && mac_idx && (iflevel <= inclevel))
		    {
			mac_offset[mac_idx-1] = DEFMACRO(bufuse) ;
			inclevel 	      = iflevel		 ;
		    }
		    continue ;	/* Insert redefinition macro after #endif */
		}
	    }
	    /*
	     * If "#define long" is already there, exit without any modification
	     */
	    else if (strncmp(cptr, "define", 6) == 0)
	    {
		cptr += 6 ;
		while (isspace(*cptr)) cptr++ ;
		if (strncmp(cptr, "long", 4) == 0)
		    exit(1) ;
		isdefine = 1;
	    }
	    else if ((cptr[0] == 'i') && (cptr[1] == 'f'))
	    {
		iflevel++	 	;
		ifline	 = linenum	;
		ifoffset = bufuse - len ;
		if (previnc)
		    continue ;
	    }
	    else if (!hascomma && ((strncmp(cptr, "else", 4) == 0) || 
				   (strncmp(cptr, "elif", 4) == 0)))
		continue ;
	    if (previnc)
	    {
		int ilevel = (ifline == linenum) ? iflevel - 1 : iflevel  ;

		if (mac_idx && (ilevel > inclevel) && 
		   (GETOFFSET(mac_offset[mac_idx-1]) < bufuse - len))
		{
		    hascomma = 1 ;
		    /*
		     * Rewind to the beginning of #include
		     */
		    iflevel = inclevel				;
		    previnc = 0					;
		    bufuse  = GETOFFSET(mac_offset[mac_idx-1])	;
		    fseek(infile, bufuse, SEEK_SET)		;
		    continue					;
		}
	    }
	    previnc = 0 ;
	    if (isdefine)
	    {
		/*
		 * Change 0L to 0 & 0UL to 0U
		 */
		goto change_line;
	    }
	}
	else
	{
	    char *comment ;
	    int   length  ;
	    if (strncmp(cptr, "using namespace", 15) == 0)
		continue ;	/* Ignore using namespace */
	    if (previnc)
	    {
		if (mac_idx && (iflevel > inclevel) && 
		   (GETOFFSET(mac_offset[mac_idx-1]) < bufuse - len))
		{
		    hascomma = 1 ;
		    /*
		     * Rewind to the beginning of #include
		     */
		    iflevel = inclevel				;
		    previnc = 0					;
		    bufuse  = GETOFFSET(mac_offset[mac_idx-1])	;
		    fseek(infile, bufuse, SEEK_SET)		;
		    continue					;
		}
	    }
	    previnc = 0 ;
	    /*
	     * Look for ; not in comment
	     */
	    if ((comment = strstr(line, "//")) != NULL)
		*comment = '\0' ;
	    if (((comment = strstr(line, "/*")) != NULL) && 
		((comment == line) || (comment[-1] != '"')))
	    {
		if (strstr(comment + 2, "*/") == NULL)
		    incomment = 1 ;
		*comment = '\0' ;
	    }
	    /*
	     * Set haslong if long is used in this source file
	     */
	    if (!haslong && ((cptr = strstr(line, "long")) != NULL))
	    {
		if (((cptr == line) || !(isalpha(cptr[-1]) || (cptr[-1] == '_'))) && 
		    (!cptr[4] 	    || !(isalpha(cptr[4 ]) || (cptr[4 ] == '_'))))
		    haslong = 1 ;
	    }
	    if (!haslong && ((strstr(line, "IMPL_FORMAT_"    ) != NULL) ||
	    		     (strstr(line, "IMPL_LINK"       ) != NULL) ||
	    		     (strstr(line, "IMPL_STATIC_LINK") != NULL) ||
	    		     (strstr(line, "DECLARE_LIST"    ) != NULL) ||
	    		     (strstr(line, "DECL_LINK"       ) != NULL) ||
	    		     (strstr(line, "DECL_STATIC_LINK") != NULL)))
		 haslong = 1 ;
	    if (!hascomma && haslong && (strchr(line, ';') != NULL))
	    {
		/* Ignore line that don't have long defined */
		hascomma = 1 ;
	    }
	    /*
	     * Look for "long double" and change it to long_double.
	     */
	    if ((cptr = strstr(line, "long double")) != NULL)
	    {
		buffer[bufuse - len + (cptr - line) + 4] = '_' ;
		printf("  Line changed: %s", line) ;
	    }
	    /*
	     * Look for "long int" and "long unsigned int" & remove the long
	     */
change_line:
	    if ((cptr = strstr(line, "long int")) != NULL)
		length = strlen("long int") ;
	    else if ((cptr = strstr(line, "long unsigned int")) != NULL)
		length = strlen("long unsigned int") ;
	    if (cptr)
	    {
		/*
		 * Skip long removal if there is alphabetic character 
		 * before or after the string
		 */
		if (((cptr > line) && isalpha(cptr[-1])) ||
		     (cptr[length] && isalpha(cptr[length])))
		    continue ;
		length = 5 ;
	    }
	    /*
	     * Change 0L to 0, 0UL to 0U, & 1L to 1.
	     */
	    else if (((cptr = strstr(line, "0L")) != NULL) ||
	    	     ((cptr = strstr(line, "1L")) != NULL))
	    {
		if (isdigit(cptr[-1]) || isalpha(cptr[-1]))
		    continue ;
		cptr++ 	   ;
		length = 1 ;
	    }	
	    else if ((cptr = strstr(line, "0UL")) != NULL)
	    {
		if (isdigit(cptr[-1]) || isalpha(cptr[-1]))
		    continue ;
		cptr  += 2 ;
		length = 1 ;
	    }	
	    if (cptr)
	    {
		memmove(buffer + bufuse - len + (cptr - line), 
			buffer + bufuse - len + (cptr - line) + length, 
			len - (cptr - line) - length) ;
		memmove(cptr, cptr + length,  len - (cptr - line) - length + 1);
		bufuse -= length ;
		len    -= length ;
		printf("  Line changed: %s", line) ;
		haslong = 1 ;
		goto change_line ;	/* Check again */
	    }
	}
    }
    if (!haslong)
	exit(1) ;	/* No long redinition needed */
    /*
     * Now write out the new file
     */
    if ((outfile = fopen(nfile, "w")) == NULL)
    {
	fprintf(stderr, "Can create output file %s!\n", nfile) ;
	exit(1) ;
    }
    wrtoff = 0 ;
    if (mac_idx > 0)
	for (idx = 0 ; idx < mac_idx ; idx++)
	{
	    int offset = GETOFFSET(mac_offset[idx]) ;
	    fwrite(buffer + wrtoff, offset - wrtoff, 1, outfile) ;
	    if (ISDEFMACRO(mac_offset[idx]))
	        fputs(define_macro, outfile) ;
	    else
	        fputs(undef_macro, outfile) ;
	    fputs("\n", outfile) ;
	    wrtoff = offset ;
	}
    else
    {
	fputs(define_macro, outfile) ;
	fputs("\n"	  , outfile) ;
    }
    fwrite(buffer + wrtoff, bufuse - wrtoff, 1, outfile) ;
    if (buffer[bufuse - 1] != '\n')
	fputs("\n"   , outfile) ;
    fputs(undef_macro, outfile) ;
    fputs("\n"	     , outfile) ;

    /*
     * Close files and replace the original file by the new file.
     */
    fclose(infile ) ;
    fclose(outfile) ;
    unlink(ofile  ) ;
    rename(filename, ofile) ;
    rename(nfile, filename) ;
    exit(0) ;
}
EOF

    cc -o $SOLENVBIN/ins_redefine $SOLENVBIN/ins_redefine.c
    rm -f $SOLENVBIN/ins_redefine.c
}

Main()
{
    Initialize $@
    if [ -z "$RESTORE" ]
    then
	Redefine_Long
    else
	Restore_Long
    fi
}

[ "$CHECK_SYNTAX" ] || Main "$@"
