// +build ignore
package main

import (
	"bufio"
	"flag"
	"fmt"
	"html/template"
	"log"
	"os"
	"regexp"
	"strconv"
)

var tmpl = `// Code generated by syscall_gen.go; DO NOT EDIT.
package main

var Syscalls = map[uint64]string{
{{ range $index, $element := . -}}
{{ $index -}}: "{{ $element }}",
{{ end -}}
}
`

var input = flag.String("input", "gen/unistd_64.h", "file to read syscalls from")
var output = flag.String("output", "syscall.go", "output filename")

func main() {
	flag.Parse()

	re := regexp.MustCompile(`^#define __NR_(\w+) (\d{1,})$`)

	syscalls := make(map[uint64]string)

	out, err := os.Create(*output)
	if err != nil {
		log.Fatal(err)
	}
	defer out.Close()

	f, err := os.Open(*input)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		matches := re.FindStringSubmatch(scanner.Text())
		if len(matches) == 0 {
			continue
		}

		id, err := strconv.ParseUint(matches[2], 10, 64)
		if err != nil {
			log.Fatal(err)
		}
		syscalls[id] = matches[1]
	}
	err = scanner.Err()
	if err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}

	t := template.Must(template.New("syscalls").Parse(tmpl))
	err = t.Execute(out, syscalls)
	if err != nil {
		log.Fatalf("execution: %s", err)
	}
}
