// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build ignore

// This program generates the table keysymCodePoints from /usr/include/X11/keysymdef.h
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"go/format"
	"io/ioutil"
	"log"
	"os"
	"regexp"
	"strings"
)

func main() {
	fh, err := os.Open("/usr/include/X11/keysymdef.h")
	if err != nil {
		log.Fatalf("opening keysymdef.h: %v", err)
	}

	defer fh.Close()

	seen := make(map[string]struct{})

	buf := &bytes.Buffer{}

	fmt.Fprintf(buf, `// generated by go generate; DO NOT EDIT.

package x11key

// keysymCodePoints maps xproto.Keysym values to their corresponding unicode code point.
var keysymCodePoints = map[rune]rune{
`)

	re := regexp.MustCompile(`^#define (XK_[^ ]*) *0x([[:xdigit:]]+) .*U\+([[:xdigit:]]+) (.+)(?: |\))\*/$`)

	s := bufio.NewScanner(fh)
	for s.Scan() {
		m := re.FindStringSubmatch(strings.TrimSpace(s.Text()))
		if m == nil {
			continue
		}

		if _, isSeen := seen[m[2]]; isSeen {
			continue
		}
		seen[m[2]] = struct{}{}

		fmt.Fprintf(buf, "0x%s: 0x%s, // %s:\t%s\n", m[2], m[3], m[1], m[4])

	}
	if err := s.Err(); err != nil {
		log.Fatalf("reading keysymdef.h: %v", err)
	}

	fmt.Fprintf(buf, "}\n")

	fmted, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatalf("formatting output: %v", err)
	}

	err = ioutil.WriteFile("table.go", fmted, 0644)
	if err != nil {
		log.Fatalf("writing table.go: %v", err)
	}
}
