// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not
// use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 represents the entry point to generate version.
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"text/template"
)

const (
	ReadWriteAccess   = 0600
	LicenseString     = "// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n\n"
	VersiongoTemplate = `// This is an autogenerated file.
// Changes made to this file will be overwritten during the build process.

// Package version contains CLI version constant and utilities.

package version

// Version is the version of the CLI
const Version = "{{.Version}}"
`
)

// version-gen is a simple program that generates the plugin's version file,
// containing information about the plugin's version
func main() {

	versionContent, err := ioutil.ReadFile(filepath.Join("VERSION"))
	if err != nil {
		log.Fatalf("Error reading VERSION file. %v", err)
	}
	versionStr := string(versionContent)

	fmt.Printf("Session Manager Plugin Version: %v\n", versionStr)

	if err := ioutil.WriteFile(filepath.Join("VERSION"), []byte(versionStr), ReadWriteAccess); err != nil {
		log.Fatalf("Error writing to VERSION file. %v", err)
	}

	versionFilePath := filepath.Join("src", "version", "version.go")

	// Generate version.go
	type versionInfo struct {
		Version string
	}
	info := versionInfo{
		Version: versionStr,
	}
	t := template.Must(template.New("version").Parse(string(LicenseString) + VersiongoTemplate))
	outFile, err := os.Create(versionFilePath)
	if err != nil {
		log.Fatalf("Unable to create output version file: %v", err)
	}
	defer outFile.Close()

	err = t.Execute(outFile, info)
	if err != nil {
		log.Fatalf("Error applying template: %v", err)
	}
}
