#/usr/bin/env sh
# vim:ft=sh

### Preprocessing 1
### Help message

csg_help() {
	echo 'Usage: csg [-h | -? | --help]
       csg <source_dir> <destination_dir> <title_format> <base_url> [<scripts_dir>]'
	[ $1 -ne 0 ] && exit $1

	echo '
Options:
  -h, -?, --help    Print this help message (also available when given no
                    arguments)

Arguments:
  <source_dir>         Folder which contains source files
  <destination_dir>    Folder in which the generated site will be put
  <title_format>       Format string for page title
                       Accepts any text or HTML, & is replaced with contents
                       title (first h1 header).
  <base_url>           Base URL of your website (scheme + authority), without
                       trailing "/", used for sitemap generation.
                       Example: https://google.com
  <scripts_dir>        Optional, folder which contains awk script for editing of
                       generated webpages.

Variables (you can predefine):
  CSG_TMP_DIR           Directory to put temporary files
                        Default: "/tmp"
  CSG_AWK               awk executable and flags
                        Default: searches for gawk

Dependencies (required):
  POSIX shell, realpath, dirname, find, cpio

Exit codes:
  1    Invalid argument
  2    No read/write access
  3    Blank argument
  4    Dependency not found

csg - complicated (static) site generator
Created by Syndamia, https://gitlab.com/Syndamia/csg'
  exit 0
}

[ -z "$1" -o "$1" = '-h' -o "$1" = '-?' -o "$1" = '--help' ] && csg_help 0

### Preprocessing 2
### Script parameters

SOURCE="$1"
[ ! -d "$SOURCE" ] && echo "[Error] $SOURCE (<source_dir>) isn't a directory or doesn't exist!" \
	&& csg_help 1
[ ! -r "$SOURCE" ] && echo "[Error] No read access to $SOURCE (<source_dir>)!" \
	&& csg_help 2

DESTINATION="$(realpath "$2")"
[ ! -d "${DESTINATION%/*}" ] && echo "[Error] Parent directory of $2 (<destination_dir>) isn't a directory or doesn't exist!" \
	&& csg_help 1
[ ! -w "${DESTINATION%/*}" ] && echo "[Error] No write access to parent directory of $2 (<destination_dir>)!" \
	&& csg_help 2

TITLEF="$3"
URL="$4"
[ -z "$URL" ] && echo "[Error] <base_url> cannot be an empty string!" \
	&& csg_help 3

USERAWKDIR="$5"
[ -n "$USERAWKDIR" -a ! -d "$USERAWKDIR" ] && echo "[Error] $USERAWKDIR (<scripts_dir>) isn't a directory or doesn't exist!" \
	&& csg_help 1

### Preprocessing 3
### "Global" variables

CSG_DIR="$(dirname "$0")"

: ${CSG_TMP_DIR:='/tmp'}
[ ! -d "$CSG_TMP_DIR" ] && echo "[Error] $CSG_TMP_DIR (\$CSG_TMP_DIR) doesn't exist!" \
	&& csg_help 1
[ ! -r "$CSG_TMP_DIR" -o ! -w "$CSG_TMP_DIR" ] && echo "[Error] No read or write permissions for $CSG_TMP_DIR (\$CSG_TMP_DIR)!" \
	&& csg_help 2

isCommand() {
	command -v "$1" >/dev/null 2>&1
}

if [ -n "$CSG_AWK" ]
then :
elif isCommand 'gawk' # GNU awk
then CSG_AWK='gawk --posix'
elif isCommand 'mawk' # Fast byte-code interpreter awk (by Mike Brennan)
then CSG_AWK='mawk -W posix'
elif isCommand 'nawk' # One true awk (by Brian Kernighan)
then CSG_AWK='nawk'
elif isCommand 'awk'  # Original or other awk
then CSG_AWK='awk'
else
	echo '[Error] Couldn'\''t find an awk implementation!'
	csg_help 4
fi

### Stage 1
### Copy everything from SOURCE to DESTINATION

(cd "$SOURCE" && \
	find . -type f -not -name "\.*" -not -name '_header.html' -not -name '_footer.html' | \
	cpio -pdu "$DESTINATION" >/dev/null 2>&1)

while read -r file
do
	[ -n "$file" ] && mv "$file" "${file%md}html"
done << EOF
$(find "$DESTINATION" -type f -name "*index.md" -links +1)
EOF

### Stage 2
### Meta

# Includes stuff which will be used in user.begin.awk
echo 'BEGIN { FILENAME=ARGV[1];FIRST="f";ALL="a"' > "$CSG_TMP_DIR/meta.begin.awk"
while read -r file
do
	$CSG_AWK -f "$CSG_DIR/md-meta.awk" "$file" >> "$CSG_TMP_DIR/meta.begin.awk" &
done << EOF
$(find "$DESTINATION" -type f -name "*.md")
EOF
wait
echo '}' >> "$CSG_TMP_DIR/meta.begin.awk"

### Stage 3
### Convertion

convert_file() {
	local file="$1"
	local outf="${file%md}html"

	$CSG_AWK \
		-f "$CSG_TMP_DIR/meta.begin.awk" -f "$USERAWKDIR/user.begin.awk" \
		-f "$CSG_DIR/md-parser.awk" \
		"$file" > "$outf"
	rm "$file"
}

while read -r file
do
	convert_file "$file" &
done << EOF
$(find "$DESTINATION" -type f -name "*.md")
EOF
wait
