website/build.sh

69 lines
1.8 KiB
Bash
Executable File

#!/bin/sh
set -euf
IFS=";"
BUILD_OUTDIR="${BUILD_OUTDIR:-./build}"
BUILD_SRCDIR="${BUILD_SRCDIR:-./src}"
BUILD_RESOURCEDIR="${BUILD_RESOURCEDIR:-./BUILD_RESOURCES}"
errecho() { echo "$@" >&2; }
clean() {
[ -f "$tmpfile" ] && rm -f "$tmpfile"
}
# "$@" here is all the keywords
build_site() {
while read -r file; do
tmpfile="$(mktemp -t website-build.XXXX)"
cp -p -f "$file" "$tmpfile"
# makes the directory structure
out="$BUILD_OUTDIR/${file#"$BUILD_SRCDIR"/}"
mkdir -p "${out%/*}"
if [ "${file##*.}" = "html" ] || [ "${file##*.}" = "php" ]; then
# this for loop call makes $@ available for internal use
grep -q -E -e '^[[:blank:]]*<!--RES .*-->$' "$tmpfile" || continue
while read -r line; do
# format: <!--RES f=file.html;var=... -->
tmp="${line% -->*}"; tmp="${tmp#*<!--RES }" # truncate beg and end
set -- $tmp
replacement="$(cat "$BUILD_RESOURCEDIR/${1##*=}")" # replacement text
shift
# variable replacement stuff
while [ -n "$*" ]; do
# replace variable fixed string
replacement="$(sd -s "var-${1%%=*}" "${1#*=}" <<-EOF
$replacement
EOF
)"
shift
done
sd -s "$line" "$replacement" "$tmpfile"
done <<-EOF
$(grep -E -e '^[[:blank:]]*<!--RES .*-->$' "$tmpfile")
EOF
fi
cmp -s "$tmpfile" "$out" >/dev/null 2>&1 && rm "$tmpfile" || mv -f "$tmpfile" "$out"
done <<-EOF
$(find "$BUILD_SRCDIR" -type f)
EOF
}
trap 'clean' INT HUP QUIT
cd "${0%/*}" # cd to script base
while getopts :o:s:r: OPT; do
case "$OPT" in
o) BUILD_OUTDIR="$OPTARG" ;;
s) BUILD_SRCDIR="$OPTARG" ;;
r) BUILD_RESOURCEDIR="$OPTARG" ;;
*) exit 1 ;;
esac
done
while [ -n "$*" ]; do
case "$1" in
clean) errecho "cleaning..." && rm -rf "$BUILD_OUTDIR" ;;
build) build_site "$BUILD_RESOURCEDIR"/* ;;
esac
shift
done