#!/usr/bin/env python3
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import json
import sys
from pathlib import Path

ROOT = Path(__file__).parent.parent

REWRITE = '_build/go/rewrite_proto.py'


# the Go version of the protobuf compiler requires the go_package option be set; modify all of our
# protobuf files to include a suitable package identifier


def main():
    generate(sys.argv[1])


def generate(manifest_file):
    with Path(manifest_file).open() as f:
        manifest = json.load(f)
    
    # Grab the complete list of known Protobuf files. For the Go build, we massage the list
    # slightly:
    # * copy google/protobuf/status.proto, but exclude it from the code to generate (one already
    #   exists out in the world, so there is no reason to build it ourselves)
    # * remove references to DAML-LF v0, because protoc for go produces code that cannot compile
    #   on account of both daml_lf_0.pb and daml_lf_1.pb both including messages named "Package"
    protos = [k for k in manifest if not k.endswith('/daml_lf_0')]
    
    print('go_gen_dir := go/v7/pkg/generated')
    print('go_proto_src := \\')
    print('  ' + ' \\\n  '.join(f'.cache/go-protos/{k}.proto' for k in protos))

    # A more accurate version of this would scan the file for an existing `option go_package` and
    # discard code generation if we decided we didn't need it; for now, simply restrict to our
    # packages (minus daml_lf_0)
    print('go_gen_src := \\')
    print('  ' + ' \\\n  '.join(f'$(go_gen_dir)/{k}.pb.go' for k in protos if k.startswith('com/daml')))

    print(f'_go_rewrite := {REWRITE}')
    print()
    print('.PHONY: gen-go')
    print('gen-go: $(go_gen_src)')
    print()

    for k in protos:
        print(f'.cache/go-protos/{k}.proto: .cache/protos/{k}.proto go/v7/go.mod')
        print('\t@mkdir -p $(@D)')
        print('\t$(python) $(_go_rewrite) $^ .cache/protos > $@')
        print('')
        print(f'$(go_gen_dir)/{k}.pb.go: $(go_proto_src) COPYRIGHT')
        print(f'\tmkdir -p $(@D)')
        print(f'\tcd go/v7 && protoc \\')
        print(f'\t  --proto_path=../../.cache/go-protos \\')
        print(f'\t  --go_out=pkg/generated \\')
        print(f'\t  --go-grpc_out=pkg/generated \\')
        print(f'\t  --go_opt=paths=source_relative \\')
        print(f'\t  --go-grpc_opt=paths=source_relative \\')
        print(f'\t  ../../.cache/go-protos/{k}.proto')
        print('')


if __name__ == '__main__':
    main()
