#!/bin/bash

AWKS="$1"
SOURCE="$2"
OUTPUT="$(realpath "$3")"
TITLEF="$4"

TIMESTAMPS="$(realpath ./timestamps.txt)"

### Helper functions

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

overwriteLine() {
	printf "\e[1A\e[K$1\n"
}

_dur=0
startTimer() {
	_dur="$(date +%s%N)"
	printf "$1\n"
}
endTimer() {
	_dur="$(echo "scale=4 ; ($(date +%s%N) - $_dur) / 1000000000" | bc -l)"
	printf "\e[1A\e[K$1    %.3fs\n" $_dur
}

### Stage 0
### Create timestamps.txt file, if necessary

if isCommand 'git'
then
	timestamps_writeDates() {
		for file in $(find . -type f -name '*.md')
		do
			dates=($(git log --follow --pretty=format:%ad --date="format:%d %B %Y" -- "$file"))
			line="$OUTPUT${file:1:-2}html\t${dates[@]: -3:3}\t${dates[@]:0:3}"
			echo -e $line >> "$TIMESTAMPS"
		done
	}

	headc=$(git rev-parse HEAD)
	if [ ! -f "$TIMESTAMPS" ] || [ "$headc" != "$(head -1 "$TIMESTAMPS")" ]
	then
	startTimer "[Stage 0] Creating timestamps file"
		echo "$headc" > "$TIMESTAMPS"
		(cd "$SOURCE" && timestamps_writeDates)
	endTimer "[Stage 0] Done"
	fi
fi

### Stage 1
### Copy everything from SOURCE to OUTPUT
startTimer "[Stage 1] Moving files to output"

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

find "$OUTPUT" -type f -name "*index.md" -links +1 | while read -r file
do
	mv "$file" "${file%md}html"
done

overwriteLine "[Stage 1] Combining awk scripts"

scr_path=()
scr_recip=()
while read -r reg; read -r scripts
do
	cat $scripts > /tmp/csg-${#scr_path[@]}.awk
	scr_path+=("/tmp/csg-${#scr_path[@]}.awk")
	scr_recip+=("$(find $OUTPUT -type f -regex "$reg")")
done < <(awk '
{
	# Remove first field
	$1=""; sub("^["FS"]*", "", $0)
	# 
	if (awks[$0] == "") awks[$0] = FILENAME
	else                awks[$0] = awks[$0] " " FILENAME

	nextfile
}
END {
	for (reg in awks) {
		print reg
		print awks[reg]
	}
}
' $(find $AWKS -type f -name "[A-Z]*.awk"))

endTimer "[Stage 1] Done"

### Stage 2
### Transforming Markdown
startTimer "[Stage 2] Transforming Markdown to HTML"

transform-file() {
	local file="$1"
	local outf="${file%md}html"
	local scripts="$2"

	# Markdown stats for a file: title, description, words, date created, date edited
	local title="$(awk '/^# / {print substr($0, 2); exit}' "$file")"
	local descr="$(awk '
	/^[[:alpha:]]/ {
		startedGathering = 1
		# Take only anchor text
		gsub(/\]\([^)]*\)/, "")
		gsub(/\[/, "")
		# Append line
		if (desc == "") desc = $0
		else desc = desc " " $0
		# Trim line to 200 characters
		if (length(desc) > 200) {
			desc = substr(desc, 1, 197) "..."
			exit
		}
	}
	startedGathering && /^$/ { exit }
	END { print desc }' "$file")"
	local words="$(wc -w "$file" | cut -d ' ' -f 1)"
	[ -n "$update_timestamps" ] && gitStats "$file" "$TIMESTAMPS"

	# Generate
	lowdown \
		--html-no-escapehtml \
		--html-no-skiphtml \
		--parse-no-metadata \
		--parse-no-autolink \
		"$file" > "$outf"

	# Run custom awk scripts
	awk --posix -f './awk-edits/#strings.awk' $scripts -f '/tmp/awk-print' "$outf" > "$outf.tmp"
	mv -f "$outf.tmp" "$outf"

	# Create final file
	awk -v title="$title" -v description="$descr" '
	/\[DESCRIPTION\]/ {
		gsub(/\[DESCRIPTION\]/, description)
	}
	/\[TITLE\]/ {
		gsub(/\[TITLE\]/, title)
	}
	{print}' "$SOURCE/_header.html" > "$file"
	cat "$outf" "$SOURCE/_footer.html" >> "$file"
	mv "$file" "$outf"
}

while read -r file
do
	scripts=""
	for i in {0..5}
	do
		[ "${scr_recip[$i]}" != "${scr_recip[$i]/${file%md}html/}" ] && scripts+="-f ${scr_path[$i]} "
	done
	transform-file "$file" "$scripts" &
done < <(find "$OUTPUT" -type f -name "*.md")
wait
endTimer "[Stage 2] Done"
