#!/bin/bash
set -e
set -o xtrace

statm()
{
    if [[ `uname` == "Darwin" ]] ; then
        stat -f '%m' $1
    elif [[ `uname` == "Linux" ]] ; then
        stat --format '%Y' $1
    fi
}

usage()
{
    echo "Usage: $0 [-ci]" 1>&2
    exit 1
}

do_clean=0
do_install=0
do_phpize=0

while getopts "cip" o; do
    case "${o}" in
        p)
            do_phpize=1
            ;;
        c)
            do_clean=1
            ;;
        i)
            do_install=1
            ;;
        *)
            usage
            ;;
    esac
done

if [[ $do_phpize == 1 || ! -e configure || $(statm config.m4) -gt $(statm configure) ]] ; then
    echo "===> Found change, scaffolding..."
    phpize --clean > /dev/null
    phpize || exit 1
fi
if [[ ! -e Makefile || $(statm configure) -gt $(statm Makefile) ]] ; then
    echo "===> Configuring..."
    ./configure > /dev/null || exit 1
fi

if [[ $do_clean == 1 ]] ; then
    echo "===> Cleaning..."
    make clean > /dev/null || exit 1
fi

echo "===> Building..."
make > /dev/null || exit 1

if [[ $do_install == 1 ]] ;then
    echo "===> Installing..."
    make install
fi
