#! /usr/bin/env bash
# Copyright (c) HashiCorp, Inc.

set -euo pipefail

# This is the officially updated list of SPDX license identifiers in JSON form
licenses=$(curl --silent https://raw.githubusercontent.com/spdx/license-list-data/master/json/licenses.json)

OUTPUT_FILE_PATH="./spdx.go"


###############
# File Header #
###############
cat <<EOF | tee "$OUTPUT_FILE_PATH"
// Copyright (c) HashiCorp, Inc.

package addlicense

// This file is autogenerated by running ./generate-spdx-list.sh

var spdxIds = []string{
EOF

###############
# Contents    #
###############

# Helper function to avoid needing to handle redirects
outfile() {
  content="$@"
  echo "$content" >> $OUTPUT_FILE_PATH
}

echo $licenses | jq '.licenses[] | select(.isDeprecatedLicenseId == false)' -c | sort | while read -r l ;do
  # this is super slow... but this script is basically never reran, sooo... meh?
  id=$(jq '.licenseId' -r <<< "$l")
  name=$(jq '.name' -r <<< "$l")
  link=$(jq '.reference' -r <<< "$l")
  outfile ""
  outfile "	// $name"
  outfile "	// $link" 
  outfile "	\"$id\","
done


###############
# File footer #
###############
cat <<EOF | tee -a "$OUTPUT_FILE_PATH"
}

// ValidSPDX takes in a string and returns true if it represents a valid SPDX ID
func ValidSPDX(id string) bool {
	for _, v := range spdxIds {
		if v == id {
			return true
		}
	}
	return false
}
EOF

go fmt $OUTPUT_FILE_PATH
