#!/usr/bin/env bash

# Copyright 2020 The Cockroach Authors.
#
# Use of this software is governed by the CockroachDB Software License
# included in the /LICENSE file.


set -eu -o pipefail

if [ $# -ne 2 ]; then
    echo "Usage: $0 <type> <package>"
    exit 1
fi

type=$1
pkg=$2
internal_pkg=$(dirname "$0")/internal
templates=(
    interval_btree_tmpl.go
    interval_btree_tmpl_test.go
)

# Make filename prefix from type. Lower case and strip pointer.
dst_prefix=$(echo ${type} | awk '{print tolower($0)}' | sed 's/*//')

# Add code generation comment to beginning of files.
gen_header_comment="// Code generated by go_generics. DO NOT EDIT.\n"

# Generate files:
# 1. strip internal/contract.go of its comments and package declaration. This
#    script originally used github.com/mmatczuk/go_generics/cmd/go_merge to
#    merge files, but that passes the AST through go/ast.MergePackageFiles,
#    which causes all "unassociated" comments (those not tied to AST nodes)
#    to be stripped due to https://github.com/golang/go/issues/20744.
# 2. for each template file, concatenate the code gen comment, the template
#    file, and the stripped contract file, remove any build tags, and pass
#    this all to go_generics.
# 3. crlfmt the result because go_generics might re-order imports.
STRIPPED=$(grep -vE '(//|package)' ${internal_pkg}/contract.go)
for template in "${templates[@]}" ; do
    dst=${dst_prefix}_${template//_tmpl/}
    echo -e ${gen_header_comment} \
    | cat - ${internal_pkg}/${template} <(echo "$STRIPPED") \
    | grep -v '//go:build ignore\|// +build ignore' \
    | go_generics -i /dev/stdin -t T=${type} -p ${pkg} -o ${dst}
    crlfmt -w -diff=false ${dst}
done
