// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you 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.

package main

import (
	"bytes"
	"compress/gzip"
	"encoding/base64"
	"flag"
	"fmt"
	"go/format"
	"io/ioutil"
	"os"
	"text/template"
)

var tpl = template.Must(template.New("bindata").Parse(`
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you 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.

// Code generated by bin_data.go - DO NOT EDIT.

package {{ .Package }}

import (
{{ if .GZip }}
	"compress/gzip"
	"bytes"
	"io"
{{- end}}
	"encoding/base64"
	"fmt"
)

var assets map[string][]byte

func asset(key string) ([]byte, error) {
	if assets == nil {
		assets = map[string][]byte{}

		var value []byte
		{{- range $asset := .Assets }}
		value, _ = base64.StdEncoding.DecodeString("{{ $asset.Data }}")
		value, _ = gzipDecode(value)
		assets["{{ $asset.Name }}"] = value{{ end }}
	}

	if value, found := assets[key]; found {
		return value, nil
	}
	return nil, fmt.Errorf("asset not found for key=%v", key)
}

func gzipDecode(data []byte) ([]byte, error) {
{{- if .GZip }}
	gz, err := gzip.NewReader(bytes.NewReader(data))
	if err != nil {
		return nil, err
	}

	out := new(bytes.Buffer)
	if _, err = io.Copy(out, gz); err != nil {
		return nil, err
	}

	return out.Bytes(), nil
{{- else }}
	// Data was not GZip encoded.
	return data, nil
{{- end }}
}
`))

type asset struct {
	Name string
	Data string
}

var assets []asset

func addAsset(key, file string) error {
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}

	// gzip the data.
	if *gzipEnabled {
		buf := new(bytes.Buffer)
		gz, err := gzip.NewWriterLevel(buf, gzip.BestCompression)
		if err != nil {
			return err
		}
		if _, err = gz.Write(data); err != nil {
			return err
		}
		if err = gz.Flush(); err != nil {
			return err
		}
		if err = gz.Close(); err != nil {
			return err
		}
		data = buf.Bytes()
	}

	assets = append(assets, asset{
		Name: key,
		Data: base64.StdEncoding.EncodeToString(data),
	})
	return nil
}

type templateVars struct {
	Package string
	GZip    bool
	Assets  []asset
}

var (
	pkgName     = flag.String("pkg", "", "package name to use in generated file")
	gzipEnabled = flag.Bool("gzip", true, "gzip contents")
)

func main() {
	flag.Parse()

	if *pkgName == "" {
		fmt.Fprintln(os.Stderr, "error: package name is required (-pkg)")
		os.Exit(1)
	}

	args := flag.Args()
	if len(args)%2 != 0 {
		fmt.Fprintln(os.Stderr, "error: expected pairs of arguments (a key and a filename)")
		os.Exit(1)
	}

	for i := 0; i < len(args); i += 2 {
		addAsset(args[i], args[i+1])
	}

	var buf bytes.Buffer
	err := tpl.Execute(&buf, templateVars{
		Package: *pkgName,
		GZip:    *gzipEnabled,
		Assets:  assets,
	})
	if err != nil {
		panic(err)
	}
	bs, err := format.Source(buf.Bytes())
	if err != nil {
		panic(err)
	}
	os.Stdout.Write(bs)
}
