#!/bin/bash

# usage:
#   $ curl -sL https://liam.sh/-/gh/g/license-header.sh | bash -s -- [path]
#   $ wget -qO- https://liam.sh/-/gh/g/license-header.sh | bash -s -- [path]

DIR="$(readlink -f "${1:-$PWD}")"

if [ ! -d "$DIR" ]; then
	echo "usage: $0 <directory>"
	exit 1
fi

export HEADER=$(curl -sL https://liam.sh/-/gh/g/license-header)

# check_header <file>
function check_header {
	if [ -n "$LICENSE_IGNORE" ]; then
		grep -Eq "$LICENSE_IGNORE" "$1" && return 0
	fi

	grep -q "DO NOT EDIT" "$1" && return 0
	grep -q "This file will be auto" "$1" && return 0
	grep -q "source code is governed" "$1" && return 0
	grep -q "This file is automatically generated" "$1" && return 0

	return 1
}

# generate_header <file-extension>
function generate_header {
	_HEADER=""
	_LINE_PREFIX=""
	_FOOTER=""

	case "$1" in
		"go") _LINE_PREFIX="// " ;;
		"ts" | "js" | "css") _HEADER="/**" _LINE_PREFIX=" * " _FOOTER=" */" ;;
	esac

	if [ -n "$_HEADER" ]; then
		echo -e "$_HEADER"
	fi

	while IFS= read -r LINE; do
		echo -e "${_LINE_PREFIX}${LINE}"
	done <<< "$HEADER"

	if [ -n "$_FOOTER" ]; then
		echo -e "$_FOOTER"
	fi

	echo ""
}

set -e

find "$DIR" \
	-type f \
	! -ipath "**/.*" \
	! -ipath "**/*.config.*" \
	! -ipath "**/*.d.*" \
	! -ipath "**/*.min.*" \
	! -ipath "**/node_modules/*" \
	! -ipath "**/dist/*" \
	! -ipath "**/test/*" \
	! -ipath "**/tests/*" \
	! -ipath "**/testdata/*" \
	! -ipath "**/tmp/*" \
	! -ipath "**/result/*" \
	! -ipath "**/results/*" \
	! -ipath "**/wailsjs/*" \
	\( -name "*.go" -o -name "*.ts" -o -name "*.js" -o -name "*.css" \) | while read -r fn; do
	if ! check_header "$fn"; then
		EXT="${fn##*.}"

		echo "adding license header to: $fn"
		{
			generate_header "$EXT"
			cat "$fn"
		} > "/tmp/license-header.tmp"
		cat < "/tmp/license-header.tmp" > "$fn"
	else
		continue
	fi
done

