#!/bin/sh

# -fオプション
flag_f=false

# 引数解析
# http://d.hatena.ne.jp/taiyo/20080211/p1
function get_args()
{
	OPT=`getopt f ${*}`  # calling getopt
	if [ $? != 0 ]; then      # option error
		echo >&2 "usage: $0 [-f] ..."
		exit 1
	fi
	
	set -- $OPT  # set result of getopt to arguments
#	echo BEFORE: $*
	
	for i; do
		case $i in
			--) break ;;
			-f) flag_f=true;;
#			-b) opt_b=true;;
#			-c) opt_c=$2; shift;;
#			-d) opt_d=$2; shift;;
		esac
		shift
	done
}

function template()
{
	src_file=${1}									# ソースファイル
	res_file=`basename ${src_file} .php`.html		# 結果ファイル

	# ソースファイルが渡されていない場合はエラー
	if [ ! -f ${src_file} ]; then
		echo "No such file: ${src_file}"
		return 1
	fi

	# 結果ファイルがある場合は、強制出力でなければ
	# ソースファイルの方が新しければHTML出力する
	if [ -f ${res_file} -a "${flag_f}" = "false" ]; then
		src_file_time=`stat -f "%m" ${src_file}`
		res_file_time=`stat -f "%m" ${res_file}`
		if [ ${src_file_time} -lt ${res_file_time} ]; then
			# ソースは変更されていないため、結果出力しない
			return 2
		fi
	fi

	src_data=`php -s ${src_file}`
	res_data=`php ${src_file}`
	cat <<EOM > ${res_file}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>${src_file}</title>
<meta http-equiv="Content-Style-Type" content="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1>${src_file}</h1>
<p id="siteDescription"></p>
<!-- / #header --></div>

<div id="res_data">
<div class="inner">

<h2>実行結果</h2>
<p>${res_data}</p>
<!-- / .inner --></div>
<!-- / #main --></div>

<div id="src_data">
<h2>ソースファイル</h2>
<p>${src_data}</p>

<!-- / #sub --></div>

<div id="footer">
<p id="copyright">Copyright &copy; 2011 <a href="/">agnode</a>. All rights reserved.</p>
<!-- / #footer --></div>

</body>
</html>
EOM
	return 0
}

# 指定したディレクトリのPHPソースファイル名一覧を取得する
function get_php_files()
{
	dir_name=${1}
	ls -la | awk '{print $9}' | grep '\.php$'
}

# program checker
function check_prog()
{
	prog_name=${1}
	printf "checking ${prog_name} ... "
	prog_path=`which ${prog_name}`
	rc=`echo $?`
	if [ "${rc}" = "0" ]; then
		echo ${prog_path}
		return 0
	else
		echo ng
		echo "Error occur check stop"
		return 1
	fi
}

function check_progs()
{
	# 一度確認済みなら処理しない
#	if [ -f check_ok ]; then
#		return 0
#	fi
	check_prog getopt || exit 1
	check_prog awk || exit 1
	check_prog php || exit 1
#	touch check_ok
}

# 使用プログラムがあるか確認する
# 失敗したら、そこで終了。
check_progs

# 引数解析
get_args ${*}

# 全てのプログラムを実行し、結果を出力する
files=(`get_php_files .`)

for file in ${files[*]}; do
	# PHPの処理結果をファイルに出力する。(成功時は出力したファイル名を表示する)
	template ${file} && echo generating `basename ${file} .php`.html
done

