package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/protoc-gen-go/plugin"
	"github.com/pkg/errors"
)

func main() {
	if err := lint(); err != nil {
		fmt.Fprintf(os.Stderr, "%v", err)
		os.Exit(1)
	}
}

func lint() error {
	data, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return errors.Wrap(err, "failed reading input")
	}

	var request plugin_go.CodeGeneratorRequest
	if err := proto.Unmarshal(data, &request); err != nil {
		return errors.Wrap(err, "failed parsing input proto")
	}

	for _, file := range request.GetProtoFile() {
		// Skip our internal change packages for this lint
		if strings.HasPrefix(file.GetPackage(), "eventbus.") {
			continue
		} else if strings.HasPrefix(file.GetName(), "google/protobuf") {
			continue // Skip 'well known types'
		}

		if err = lintFields(file); err != nil {
			return errors.Wrap(err, "failed linting fields")
		}

		if err = lintSchemaName(file); err != nil {
			return errors.Wrap(err, "failed linting schema names")
		}
	}

	return nil
}
