// Copyright 2016 The Roughtime Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Modifications copyright 2018 Cloudflare, Inc.

// This package defines some functionalities useful for building Roughtime
// clients. It's based on Google's original Go implementation of Roughtime. For
// more information, visit https://roughtime.googlesource.com/roughtime/.
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/cloudflare/roughtime/client"
)

const (
	inputJSONFile string = "ecosystem.json"
	outputGoFile  string = inputJSONFile + ".go"
)

func main() {
	client.SetLogger(log.New(os.Stderr, "", log.LstdFlags))
	servers, skipped, err := client.LoadConfig(inputJSONFile)
	if err != nil {
		panic(err)
	}
	if skipped > 0 {
		fmt.Printf("skipped %v servers", skipped)
	}

	file, err := os.Create(outputGoFile)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	fmt.Fprint(file, filePrefix)
	for _, server := range servers {
		fmt.Fprintf(file, "\t{\n")
		fmt.Fprintf(file, "\t\tName:          \"%v\",\n", server.Name)
		fmt.Fprintf(file, "\t\tVersion:       \"%v\",\n", server.Version)
		fmt.Fprintf(file, "\t\tPublicKeyType: \"%v\",\n", server.PublicKeyType)

		fmt.Fprint(file, "\t\tPublicKey:     []byte{")
		for i, b := range server.PublicKey {
			fmt.Fprint(file, b)
			if i < len(server.PublicKey)-1 {
				fmt.Fprint(file, ", ")
			}
		}
		fmt.Fprintln(file, "},")

		fmt.Fprintln(file, "\t\tAddresses: []config.ServerAddress{")
		for _, address := range server.Addresses {
			fmt.Fprintln(file, "\t\t\t{")
			fmt.Fprintf(file, "\t\t\t\tProtocol: \"%v\",\n", address.Protocol)
			fmt.Fprintf(file, "\t\t\t\tAddress:  \"%v\",\n", address.Address)
			fmt.Fprintln(file, "\t\t\t},")
		}
		fmt.Fprintln(file, "\t\t},")
		fmt.Fprintln(file, "\t},")
	}
	fmt.Fprintln(file, "}")
}

const (
	filePrefix string = `// Code generated by "ecosystem_json_go_builder". DO NOT EDIT.
// source: ecosystem.json
package roughtime

import "github.com/cloudflare/roughtime/config"

var Ecosystem = []config.Server{
`
)
