#!/bin/sh

die() {
    >&2 echo "error: $@"
    exit 1
}

set -e

PHP="$(which php)"
SCRIPT_DIR=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
APP_DIR="$(realpath "$SCRIPT_DIR/../")"
OUTPUT_ROOT_DIR=

while [ $# -gt 0 ]; do
	case $1 in
		-o) OUTPUT_ROOT_DIR="$2"; shift ;;
		-h) usage ;;
		*) die "unexpected argument: $1" ;;
	esac
	shift
done
[ -z "$OUTPUT_ROOT_DIR" ] && die "you must specify output directory"

for project in ic foreignone; do
	"$SCRIPT_DIR"/util/build_css.sh -i "$APP_DIR/public/$project/scss" -o "$OUTPUT_ROOT_DIR/public/$project/dist-css"                 || die "build_css failed"
	"$SCRIPT_DIR"/util/build_js.sh -i "$APP_DIR/public/common/js" -o "$OUTPUT_ROOT_DIR/public/$project/dist-js"                       || die "build_js failed"
	$PHP "$SCRIPT_DIR"/util/gen_runtime_config.php --commit-hash "$(git rev-parse --short=8 HEAD)" > "$OUTPUT_ROOT_DIR/config-runtime.php" || die "gen_runtime_config failed"
done
