//go:build ignore

package main

import (
	"archive/zip"
	"bytes"
	"flag"
	"fmt"
	"os"
	"text/template"
)

var tmpl = `// Code generated by "go run gen.go". DO NOT EDIT.
//go:generate env ZONEINFO=$GOROOT/lib/time/zoneinfo.zip go run gen.go -output tzdata.go
package tzdata
var TimeZones = []string{
	{{- range . }}
	"{{.}}",
	{{- end }}
}
`

var filename = flag.String("output", "tzdata.go", "output file name")

func main() {
	flag.Parse()

	path := os.Getenv("ZONEINFO")
	if path == "" {
		fmt.Println("ZONEINFO is not set")
		os.Exit(1)
	}

	if _, err := os.Stat(path); os.IsNotExist(err) {
		fmt.Printf("ZONEINFO %s does not exist\n", path)
		os.Exit(1)
	}

	zipfile, err := zip.OpenReader(path)
	if err != nil {
		fmt.Printf("Error opening ZONEINFO %s: %v\n", path, err)
		os.Exit(1)
	}
	defer zipfile.Close()

	timezones := []string{}

	for _, file := range zipfile.File {
		timezones = append(timezones, file.Name)
	}

	var buf bytes.Buffer

	tmpl, err := template.New("tzdata").Parse(tmpl)
	if err != nil {
		fmt.Printf("Error parsing template: %v\n", err)
		os.Exit(1)
	}

	err = tmpl.Execute(&buf, timezones)
	if err != nil {
		fmt.Printf("Error executing template: %v\n", err)
		os.Exit(1)
	}

	err = os.WriteFile(*filename, buf.Bytes(), 0644)
	if err != nil {
		fmt.Printf("Error writing file %s: %v\n", *filename, err)
		os.Exit(1)
	}
}
