// Run with: go run ./scripts/check-sh-input.go content/post.md
package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strings"

	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/ast"
	"github.com/yuin/goldmark/text"
)

func checkMarkdown(path string, source []byte, output io.Writer) (checked, failed int) {
	document := goldmark.DefaultParser().Parse(text.NewReader(source))
	_ = ast.Walk(document, func(node ast.Node, entering bool) (ast.WalkStatus, error) {
		block, ok := node.(*ast.FencedCodeBlock)
		if !entering || !ok || string(block.Language(source)) != "sh" || block.Info == nil {
			return ast.WalkContinue, nil
		}
		role := ""
		for _, field := range strings.Fields(string(block.Info.Segment.Value(source)))[1:] {
			if field == "input" || field == "output" {
				role = field
			}
		}
		if role != "input" {
			return ast.WalkContinue, nil
		}
		checked++
		line := bytes.Count(source[:block.Info.Segment.Start], []byte("\n")) + 1
		var script bytes.Buffer
		if block.Lines().Len() > 0 {
			first := block.Lines().At(0)
			// Preserve Markdown line numbers in the shell's diagnostics.
			script.WriteString(strings.Repeat("\n", bytes.Count(source[:first.Start], []byte("\n"))))
		}
		for i := 0; i < block.Lines().Len(); i++ {
			segment := block.Lines().At(i)
			script.Write(segment.Value(source))
		}
		command := exec.Command("sh", "-n")
		command.Stdin = &script
		diagnostics, err := command.CombinedOutput()
		if err != nil {
			failed++
			fmt.Fprintf(output, "%s:%d: sh input block failed: %v\n%s", path, line, err, diagnostics)
		}
		return ast.WalkContinue, nil
	})
	return checked, failed
}

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "usage: go run ./scripts/check-sh-input.go FILE.md")
		os.Exit(2)
	}
	path := os.Args[1]
	source, err := os.ReadFile(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	checked, failed := checkMarkdown(path, source, os.Stderr)
	fmt.Printf("%s: checked %d sh input blocks; %d failed\n", path, checked, failed)
	if failed > 0 {
		os.Exit(1)
	}
}
