#!/bin/sh

## WebMake
## Simple templated static webpage generator.

PROJECTDIR="${PROJECTDIR:-$PWD}"
PROJECTSRC="$PROJECTDIR/src"
PROJECTOUT="$PROJECTDIR/http-out"
TEMPLATES="$PROJECTDIR/templates"

CLEAN="N"
REENCODE="N"
OVERWRITE="Y"
OPTIMIZE="Y"
EXCLUDE=""

(command -v optipng &> /dev/null)
HAS_OPTIPNG=$?
(command -v jpegoptim &> /dev/null)
HAS_JPEGOPTIM=$?
(command -v gifsicle &> /dev/null)
HAS_GIFSICLE=$?

echo "WebMake v4 by Wirlaburla"

help() {
echo "$(basename "$0") [-ceOopx] (init|make|clean)

modes:
	init        initailizes project
	make        builds project
	clean       cleans project output

options:
	-c=[Y|N], --clean=[Y|N]
		(default=N) Clean project output directory.
	
	-e=[Y|N], --re-encode=[Y|N]
		(default=N) Re-encode media files with FFMPEG.
	
	-O=[Y|N], --overwrite=[Y|N]
		(default=Y) Overwrite files in output directory.
	
	-o=[Y|N], --optimize=[Y|N]
		(default=Y) Optimize PNG, GIF, and JPEG images.
	
	-p=<path>, --project=<path>
		(default=\"\$PWD\") Use defined project directory.
	
	-x=<paths>, --exclude=<paths>
		(defualt="") Exclude source directories from make. Separator is ':'."
}

handle() {
for i in $1/*;
do
	mime=$(file -b --mime-type "$i")
	relpath=$(realpath --relative-to="$PROJECTSRC" "$i")
	if [[ $mime = 'inode/directory' ]]; then
		if [[ ! ":$EXCLUDE:" == *":$relpath:"* ]]; then
			echo "Changing directory: $relpath"
			mkdir -p "$PROJECTOUT/$relpath"
			handle "$i"
		fi
	elif [ $OPTIMIZE = 'Y' ] && [[ $mime = 'image/png' ]] && [ $HAS_OPTIPNG -eq 0 ]; then
		echo "Optimizing PNG: $relpath"
		optipng -quiet "$i" -out "$PROJECTOUT/$relpath"
	elif [ $OPTIMIZE = 'Y' ] && [[ $mime = 'image/gif' ]] && [ $HAS_GIFSICLE -eq 0 ]; then
		echo "Optimizing GIF: $relpath"
		gifsicle -i "$i" -O3 -o "$PROJECTOUT/$relpath"
	elif [ $OPTIMIZE = 'Y' ] && [[ $mime = 'image/jpeg' ]] && [ $HAS_JPEGOPTIM -eq 0 ]; then
		echo "Optimizing JPEG: $relpath"
		cp "$i" "$PROJECTOUT/$relpath"
		jpegoptim -q "$PROJECTOUT/$relpath"
	elif [ $REENCODE = 'Y' ] && ( [[ ${mime:0:5} = 'video' ]] || [[ ${mime:0:5} = 'audio' ]] ) && command -v ffmpeg &> /dev/null; then
		echo "Re-Encoding File: $relpath"
		ffmpeg -y -i "$i" "$PROJECTOUT/$relpath"
	elif [[ ${i: -4} == ".cnt" ]]; then
		echo "Processing file: $relpath"
		FILETEMPLATE="$TEMPLATES"/"$(head -n 1 $i)"

		FILE=$(cat $FILETEMPLATE)

		PAGE_SECTIONS="$(pcregrep -N CR -M -o1 '<#(?<tag>[a-z@]+)>(.*?)(?:<\k<tag>#>)' $i)"
		for m in $PAGE_SECTIONS; do
			PAGE_MATCH="$(pcregrep -N CR -M -o2 \<#\(?\<tag\>$m\)\>\(.*?\)\(?:\<\\k\<tag\>#\>\) $i)"

			FILE=${FILE//\$$m\$/"$PAGE_MATCH"}
		done

		echo "$FILE" > "$PROJECTOUT/${relpath%.cnt}.${FILETEMPLATE##*.}"
	elif ! [[ $mime = 'image/x-xcf' ]]; then
		if [ $OVERWRITE = 'Y' ] || [[ ! -f "$PROJECTOUT/$relpath" ]]; then
			echo "Copying file: $relpath"
			cp "$i" "$PROJECTOUT/$relpath"
		fi
	fi
done
}

clean() {
	if [[ -d "$PROJECTOUT" ]]; then
		rm -rf $PROJECTOUT
	fi
}

init() {
	echo "Initializing project..."
	mkdir -p $PROJECTSRC
	mkdir -p $TEMPLATES
	echo -e "default.html\n<#sitename>My Site<sitename#>\n<#title>My Templated Page<title#>\n<#content>\n<p>Hi, this is my static generated content!</p>\n<content#>" > "$PROJECTSRC/index.cnt"
	echo -e "<!DOCTYPE html>\n<html>\n<head>\n<title>\$title$ - \$sitename$</title>\n</head>\n<body>\n\$content$</body>\n</html>" > "$TEMPLATES/default.html"
	echo "Project initialized! Edit your templates in 'templates/' and place your source web files in 'src/'. Run subcommand make in the project directory to generate your static pages."
	exit
}

makeweb() {
	if [[ $CLEAN = "Y" ]]; then
		clean
	fi
	echo "Making project..."
	mkdir -p $PROJECTOUT
	handle "$PROJECTSRC"
	echo "Make complete!"
	exit
}

for i in "$@"; do
case $i in
	-p=*|--project=*)
	PROJECTDIR="${i#*=}"
	PROJECTSRC="$PROJECTDIR/src"
	PROJECTOUT="$PROJECTDIR/http-out"
	TEMPLATES="$PROJECTDIR/templates"
	
	;;
	--clean=*|-c=*)
	CLEAN="${i#*=}";;
	--re-encode=*|-e=*)
	REENCODE="${i#*=}";;
	--overwrite=*|-O=*)
	OVERWRITE="${i#*=}";;
	--optimize=*|-o=*)
	OPTIMIZE="${i#*=}";;
	--exclude=*|-x=*)
	EXCLUDE="${i#*=}";;
	init)
	init;;
	make)
	makeweb;;
	clean)
	clean
	exit;;
	*)
	echo "Unknown arguments: $i"
	exit
	;;
esac
done
help