#!/bin/bash
# convert php5 program to $2 php4 program leave it as php5 and php4 file and link to php extention
PATH=/bin:/usr/bin
WD=`pwd`
EXIT=0
for file
do
    cd $WD
    if [ ! -f "$file" ] ; then echo "$file" does not exits. ; continue; fi
    if ! grep -q -e "private.*function" -e "public.*function" -e "protected.*function" -e "protected.*[;=]" -e "public.*[;=]" -e "private.*[;=]" "$file"
    then
        echo no php5 specials found in $file, leave it untouched ; continue
    fi
    FILE=`basename "$file" | sed 's/.[Pp][Hh][Pp]$//'`
    if [ x"$FILE" = x ] 
        then echo "$file is not .php file. Leave it untouched"; continue
    fi
    if [ -f "$file"5  -o -h "$file" ] ; then rm -f "$file"; cp "$file"5 "$file"; chmod u+w "$file"; fi
    DIR=`dirname "$file"`
    cd "$DIR"
    if grep -q -e "\*/ var " `basename "$file"`
    then
	ln -s -f `basename "$file"` "$FILE.php5"
	echo "$file is already converted php4 file! Leave it untouched" ;
	continue
    fi
    if ! ln -s -f `basename "$file"` "$FILE.php5"
    then
        echo "cannot link original file $file to $FILE.php5" >/dev/stderr ; EXIT=1; continue
    fi
    if cp -f "$FILE.php5" "$FILE.php4"
    then
	chmod u+w "$FILE.php4"
	echo created "$FILE.php5 (link to $FILE.php) and $FILE.php4 file"
        if grep -q __construct "$FILE.php4"
        then
            CLASS=`grep "class[ \t][ \t]*[A-Za-z0-9][A-Za-z0-9_]*[ \t][ \t]*{"  "$FILE.php4" | sed "s/.*class[ \t][ \t]*\\([A-Za-z][A-Za-z0-9_]*\\)[ \t][ \t]*{.*/\\1/"`
            echo "found class $CLASS"
        else CLASS="__CONSTRUCT"
        fi
        ed - "$FILE.php4" <<EOF
g/function/s%private[ \t][ \t]*function%/*private*/ function%
g/function/s%public[ \t][ \t]*function%/*public*/ function%
g/function/s%protected[ \t][ \t]*function%/*protected*/ function%
g/function.*__construct/s%__construct%/*__construct*/ ${CLASS}%
g/function.*__destruct/s%__destruct%/*__destruct*/ ${CLASS}Destruct%
g/private.*[;=]/s%private[ \t][ \t]*%/*private*/ var %g
g/public.*[;=]/s%public[ \t][ \t]*%/*public*/ var %g
g/protected.*[;=]/s%protected[ \t][ \t]*%/*protected*/ var %g
w
q
EOF
# specialty for tcpdf.php
        if grep -q "return.*html_entity_decode(" "$FILE.php4"
        then
            ed - "$FILE.php4" <<EOF
/class_exists/i
/**
 * HTML entity decode functions
 * added next statement for PHP4
 */
require_once(dirname(__FILE__)."/html_entity_decode_php4.php");
.
/return.*html_entity_decode(/i
/*
 * added next if statement for PHP4
 */
			if (!\$this->isunicode) {
				return html_entity_decode(\$text_to_convert);
			}
.
g/html_entity_decode(\$text_to_convert, ENT_QUOTES, \$this->encoding);/s%%/* & */ html_entity_decode_php4(\$text_to_convert);%
g/ers.*4\\.0\\.0/s/4\\.0\\.[0-9][0-9]*/&_PHP4/
g/TCPDF.*4\\.0\\.0/s/4\\.0\\.[0-9][0-9]*/&_PHP4/
w
q
EOF
        fi
        echo "converted $FILE.php to $FILE.php4"
    else
	echo "could not convert $file" >/dev/stderr; EXIT=1
    fi
done
exit $EXIT
