#! /bin/bash
### file ~/bin/myTemplateToPHP.sh

### Description: Replace simple placeholders with PHP-native syntax.
### Version: 1.1.3

htmlSafeMode='yes';
placeHolderLeft='{{';
placeHolderRight='}}';

if [ "no" == ${htmlSafeMode} ]; then
    replacementLeft="<?=\$tpl['";
    replacementRight="'];?>";
else
    replacementLeft="<?=htmlspecialchars\( \$tpl['";
    replacementRight="'] \);?>";
fi

placeHolderLeft=$(echo  ${placeHolderLeft}  | sed 's/#/\\#/g');
placeHolderRight=$(echo ${placeHolderRight} | sed 's/#/\\#/g');
replacementLeft=$(echo  ${replacementLeft}  | sed 's/#/\\#/g');
replacementRight=$(echo ${replacementRight} | sed 's/#/\\#/g');

sedSkriptFile=$(mktemp --suffix '.sed');
echo "s#${placeHolderLeft}#${replacementLeft}#g"    > "${sedSkriptFile}";
echo "s#${placeHolderRight}#${replacementRight}#g" >> "${sedSkriptFile}";

while [ $1 ]; do
    fileIn=$1;
    fileOut=$(echo ${fileIn} | sed -s 's#\.txt$#.php#i');
    if [ ${fileOut} != ${fileIn} ]; then
        if [ -r "${fileIn}" ]; then
            touch "${fileOut}";
            sed -f "${sedSkriptFile}" < ${fileIn} > "${fileOut}";
            if [ "0" == "$?" ]; then
                echo "Success: Has generated the '${fileOut}' from '${fileIn}'";
            else
                echo "Error: Can't generate '${fileOut}' from '${fileIn}' Can you write '${fileOut}'?";
                hasErrors='1';
            fi
        else
            echo "Error: Can't read from '${fileIn}'. Filename incorrect? Rights?";
            hasErrors='1';
        fi
    else
        echo "Error: Input File  '${fileIn}' ending on '.php'. This is unwanted. Rename the File to '.txt' or show your argumentlist. (Do not start ${0} with asterix as argumentlist)";
        hasErrors='1';
    fi
    shift;
done;

if [ hasErrors == "1" ]; then
    echo "You can show the sed-skript: '${sedSkriptFile}'";
else
    rm "${sedSkriptFile}";
fi