package main

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

type Line struct {
	Text string
	Look bool
}

type Section struct {
	Title string
	Lines []Line
}

// fields calls each with the words of every line of a file
func fields(name string, each func(part []string)) error {
	f, err := os.Open(name)
	if err != nil {
		return err
	}
	defer f.Close()
	in := bufio.NewScanner(f)
	for in.Scan() {
		each(strings.Fields(in.Text()))
	}
	return in.Err()
}

func collect(limit int) ([]Section, error) {
	var volumes, disks []Line
	err := fields("df.txt", func(part []string) {
		if len(part) != 6 || part[0] == "Filesystem" {
			return
		}
		used, _ := strconv.Atoi(strings.TrimSuffix(part[4], "%"))
		volumes = append(volumes, Line{fmt.Sprintf("%s %d percent used", part[5], used), used >= limit})
	})
	if err != nil {
		return nil, err
	}
	err = fields("smartctl.txt", func(part []string) {
		if len(part) < 10 {
			return
		}
		raw, _ := strconv.Atoi(part[9])
		text := fmt.Sprintf("%s %d", part[1], raw)
		switch part[1] {
		case "Reallocated_Sector_Ct", "Current_Pending_Sector":
			disks = append(disks, Line{text, raw > 0})
		case "Temperature_Celsius":
			disks = append(disks, Line{text, raw >= 50})
		}
	})
	if err != nil {
		return nil, err
	}
	errors := 0
	err = fields("nas.log", func(part []string) {
		if len(part) > 2 && part[2] == "ERROR" {
			errors++
		}
	})
	log := []Line{{fmt.Sprintf("%d errors", errors), errors > 0}}
	return []Section{{"Volumes", volumes}, {"Disks", disks}, {"Log", log}}, err
}

const page = `<h1>NAS report</h1>
{{range .}}<h2>{{.Title}}</h2>
{{range .Lines}}<p{{if .Look}} class="look"{{end}}>{{.Text}}</p>
{{end}}{{end}}`

func main() {
	limit := flag.Int("limit", 90, "percent that counts as full")
	html := flag.Bool("html", false, "print a web page")
	flag.Parse()

	sections, err := collect(*limit)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	if *html {
		if err := template.Must(template.New("page").Parse(page)).Execute(os.Stdout, sections); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(2)
		}
	}
	bad := 0
	for _, s := range sections {
		if !*html {
			fmt.Println(s.Title)
		}
		for _, l := range s.Lines {
			mark := "ok  "
			if l.Look {
				mark = "LOOK"
				bad++
			}
			if !*html {
				fmt.Println(" ", mark, l.Text)
			}
		}
	}
	if !*html {
		fmt.Println(bad, "lines need a look")
	}
	if bad > 0 {
		os.Exit(1)
	}
}
