#!/bin/bash

### Checking for find
echo -n "Locating 'find'... "
FIND=`which find`
if [[ -x $FIND ]]; then
   echo $FIND
else
   echo not found\!
   echo ERROR: Unable to locate find utility
   exit 1
fi

### Checking for xargs
echo -n "Locating 'xargs'... "
XARGS=`which xargs`
if [[ -x $XARGS ]]; then
   echo $XARGS
else
   echo not found\!
   echo ERROR: Unable to location xargs
   exit 1
fi

### Checking for sed
echo -n "Locating 'sed'... "
SED=`which sed`
if [[ -x $SED ]]; then
   echo $SED
else
   echo not found\!
   echo ERROR: Unable to locate sed
   exit 1
fi

### Checking for touch
echo -n "Locating 'touch'... "
TOUCH=`which touch`
if [[ -x $TOUCH ]]; then
   echo $TOUCH
else
   echo not found\!
   echo ERROR: Unable to locate touch
   exit 1
fi

### Delete old tmp files
echo -n "Deleting old temp files... "
$FIND . -type f -name \*.tmp\*|$XARGS rm -f
echo done

### Find installed PHP binary ###
echo -n "Finding PHP binary... "
PHP_BIN=`which php`
if [[ $? == "0" ]]; then
   echo $PHP_BIN
   $FIND . -type f -name \*.in -print|while read file; do $SED "s^%%PHP_BIN%%^$PHP_BIN^" < $file > $file.tmp; $TOUCH -r $file $file.tmp; done
else
   echo not found\!
   echo FAILED: Cannot find PHP binary\!
   exit 1
fi

### Checking PHP version
echo -n "Checking PHP version... "
PHP_VER=`$PHP_BIN -r "echo version_compare(PHP_VERSION, '5.0.0', 'ge') ? PHP_VERSION : 0;"`
if [[ $? == "0" && $PHP_VER != "0" ]]; then
   echo $PHP_VER
else
   echo "unsupported PHP version!"
   echo FAILED: PHP 5.0.0 or higher required\!
   exit 1
fi

### Checking PHP SAPI
echo -n "Checking PHP SAPI... "
PHP_SAPI=`$PHP_BIN -r "echo php_sapi_name();"`
if [[ $? == "0" && $PHP_SAPI == "cli" ]]; then
   echo $PHP_SAPI
else
   echo "unsupported PHP SAPI!"
   echo FAILED: only 'cli' SAPI is supported\!
   exit 1
fi

### Checking install path
echo -n "Checking install path... "
if [[ $# > 0 ]]; then
   echo $1
   INST_PATH=$1
else
   echo "using defaults"
   INST_PATH=""
fi
$FIND . -type f -name \*.tmp -print|while read file; do $SED "s^%%INST_ROOT%%^$INST_PATH^" < $file > ${file/%.in*}; $TOUCH -r $file ${file/%.in*}; done

### Writing Makefile
echo -n "Writing Makefile... "
if [[ ! -f Makefile ]]; then
   echo ERROR: Makefile does not exist\!
   exit 1
else
   mv Makefile Makefile.in.tmp
fi
TAR=`which tar`
INSTALL=`which install`
CHOWN=`which chown`
if [[ ! -x $TAR || ! -x $INSTALL || ! -x $CHOWN ]]; then
   echo FAILED\!
   echo "Unable to locate tar, install, and/or chown"
   exit 1
else
   $SED "s^%%TAR%%^$TAR^" < Makefile.in.tmp|$SED "s^%%INSTALL%%^$INSTALL^"|$SED "s^%%CHOWN%%^$CHOWN^" > Makefile; $TOUCH -r Makefile.in.tmp Makefile
   echo done
fi

### Cleanup
$FIND . -type f -name \*.tmp -print|$XARGS rm -f
