#!/usr/bin/env bash

# execute: ./scripts/add_descriptions_to_readme.sh

# define new line character to be u"$SED_COMMAND" in `"$SED_COMMAND"`
nl='
'

SED_COMMAND="sed"

if [[ "$OSTYPE" == "darwin"* ]]; then
	SED_COMMAND="gsed"
fi

# enable regex (see: https://stackoverflow.com/a/42740385)
shopt -s extglob

scriptName="$(dirname "$0")/$(basename "$0")"

function getHelp() { # get descriptions and commands from Makefile
	i=0
	commands=()
	descriptions=()

	while read -r line; do
		if (( i % 2 == 0 ));
			then
				descriptions+=( "${line//#:*( )}" )
			else
				commands+=( "$(echo "$line" | cut -d : -f 1)" )
		fi
		((i++))
	done < <(
		# https://stackoverflow.com/a/59087509
		grep -B1 -E "^[a-zA-Z0-9_-]+:([^\=]|$)" ./Makefile \
		| grep -v -- --
	)
}

FILE=README.md

# returns `commands` and `descriptions` arrays
getHelp

startLine=$(( $( grep -n "^#### Available Commands" $FILE | cut -d : -f 1 ) + 2 ))
endLine=$(( $( grep -n "^#### File Structure" $FILE | cut -d : -f 1 ) - 2 ))

# Updates "Available Commands" section
if (( startLine <= endLine));
then
	# Deletes previous descriptions
	"$SED_COMMAND" -i "$startLine,${endLine}d" "$FILE"
fi

function createMultipleAsterisks() {
	numOfAsterisks=$1
	asterisks=$( eval printf "\*%.0s" "{1..${numOfAsterisks}}" )
	echo "$asterisks"
}

function printAvailableCommands() {
	curLine=$startLine
	stringToWrite="<!--- GENERATED by $scriptName --->"
	commentLen=$(( ${#stringToWrite} - 11 ))
	i=0

	"$SED_COMMAND" -i "${curLine}i\\${stringToWrite}" "$FILE"

	# https://www.shellcheck.net/wiki/SC2219
	(( curLine++ )) || true

	# empty line
	"$SED_COMMAND" -i "${curLine}i${nl}" "$FILE"

	(( curLine++ )) || true

	echo 'Writing the following commands with their descriptions:'
	while (( i < ${#commands[@]} ))
	do
		stringToWrite="- \`make ${commands[$i]}\`: ${descriptions[$i]}."
		stringToWrite=${stringToWrite//\'/\\\'}
		echo "$stringToWrite"

		"$SED_COMMAND" -i "${curLine}i\\${stringToWrite}" "$FILE"
		(( curLine++ )) || true

		(( i++ )) || true
	done

	# empty line
	"$SED_COMMAND" -i "${curLine}i${nl}" "$FILE"
	(( curLine++ )) || true

	# multiple '*'
	asterisks=$(createMultipleAsterisks $commentLen)
	stringToWrite="<!--- ${asterisks} --->"
	"$SED_COMMAND" -i "${curLine}i\\${stringToWrite}" "$FILE"

	(( curLine++ )) || true
}

echo 'Updating "Available Commands" section...'

printAvailableCommands

echo 'Done.'

