#!/bin/bash
#
# phpStylist.php を利用した PHPファイルの整形
# encoding-hint: utf-8
# 
# - 使い方
#  - chmod 700 phpStylist.sh
#  - ./phpStylist.sh INPUT-DIR OUTPUT-DIR
#
# - 参考
#   - http://d.hatena.ne.jp/Tetsujin/20070803/1186068184
#
# $Revision$

# include conf
CUR_DIR=$(cd $(dirname $0);pwd)

# define vars
CMDNAME=`basename $0`
CUR_USER=`whoami`
INPUT_DIR=$1
OUTPUT_DIR=$2

# setup
setup() {
	php=`which php`
	stylist="phpStylist.php"

	find "$INPUT_DIR" -type f -name "*.php" | grep -v ".svn" | while read file; do
		outfile=`echo $file | sed -e "s/$INPUT_DIR/$OUTPUT_DIR/"`
		outdir=`dirname $outfile`
		
		if [ ! -d $outdir ]; then
			mkdir -p $outdir
		fi

		$php $stylist "$file" \
		--indent_size 4 \
		--keep_redundant_lines \
		--space_after_comma \
		--space_around_assignment \
		--align_var_assignment \
		--space_around_comparison \
		--space_around_arithmetic \
		--space_around_logical \
		--space_around_colon_question \
		--line_before_curly_function \
		--space_after_if \
		--else_along_curly \
		--add_missing_braces \
		--line_after_break \
		--space_inside_for \
		--indent_case \
		--vertical_array \
		--align_array_assignment \
		--space_around_double_arrow \
		--space_around_concat \
		--line_before_comment_multi \
		> "$outfile"
		
	done
}

usage() {
	echo "Usage: $CMDNAME INPUT-DIR OUTPUT-DIR"
}

# start

# オプション解析
while getopts h: OPT
do
	case $OPT in
		* )
			usage
			exit 1;;
	esac
done
# オプション部分を切り捨てる。
shift `expr $OPTIND - 1`

# start

if [ $# -le 0 ]; then
	usage
	exit 1
fi

if [ "$INPUT_DIR" == "" -o ! -d "$INPUT_DIR" ]; then
	echo "Error : Can't open dir. [$INPUT_DIR]"
	exit 1
fi

if [ "$OUTPUT_DIR" == "" -o ! -d "$OUTPUT_DIR" ]; then
	echo "Error : Can't open dir. [$OUTPUT_DIR]"
	exit 1
fi

if [ "$INPUT_DIR" == "$OUTPUT_DIR" ]; then
	echo "Error : INPUT_DIR = OUTPUT_DIR"
	exit 1
fi

while [ 1 ]; do
    echo -n "Execute phpStylist ? Type Yes/No: "
    read line
    case $line in
    [yY][eE][sS])
        setup
        break
    ;;
    [nN][oO])
        echo "abort"; break
    ;;
    esac
done
