#!/bin/sh

set -e
set -x

SRCPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
outfile=dependencies.csv

while :; do
	case $1 in
		--csv)
			if [ "$2" ]; then
				outfile=$2
			else
				echo "ERROR: --csv needs a non-empty argument"
				exit 1
			fi
			shift
			;;
		--csv=?*)
			outfile=${1#*=}
			;;
		--csv=)
			echo "ERROR: --csv needs a non-empty argument"
			exit 1
			;;
		*)
			break
			;;
	esac

	shift
done

go mod tidy
go mod download
go list -m -json all $@ | go run go.elastic.co/go-licence-detector \
		-includeIndirect \
		-rules "$SRCPATH/notice/rules.json" \
		-overrides "$SRCPATH/notice/overrides.json" \
		-noticeTemplate "$SRCPATH/notice/dependencies.csv.tmpl" \
		-noticeOut "$outfile" \
		-depsOut ""


# Fill-in required values for UBI images
# Check headers in $SRCPATH/notice/dependencies.csv.tmpl:
# name,url,version,revision,license
ubiurl='https://catalog.redhat.com/software/containers/ubi9/ubi-minimal/615bd9b4075b022acc111bf5'
ubisource='https://oss-dependencies.elastic.co/red-hat-universal-base-image-minimal/9/ubi-minimal-9-source.tar.gz'
ubilicense='Custom;https://www.redhat.com/licenses/EULA_Red_Hat_Universal_Base_Image_English_20190422.pdf'
cat <<EOF >> $outfile
Red Hat Universal Base Image minimal,$ubiurl,9,,$ubilicense,$ubisource
EOF
