// This file is part of the adequate Debian-native package, and is available
// under the Expat license. For the full terms please see debian/copyright.

package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
)

func tellDebconf(tags []string) {
	dc := initDebconf()

	const t = "adequate/error"
	dc.tell(fmt.Sprintf("capb escape"))
	dc.tell(fmt.Sprintf("FSET %s seen false", t))

	ss := strings.Join(tags, "\\n")
	if len(ss) > 1024*64 {
		ss = fmt.Sprintf("Found too many policy violations to report " +
			"via debconf. Please run instead manually: adequate --all")
	}
	dc.tell(fmt.Sprintf("SUBST %s tags %s", t, ss))

	dc.tell("TITLE adequate found packaging bugs")
	dc.tell(fmt.Sprintf("INPUT critical %s", t))
	dc.tell("GO")
	if err := dc.stop(); err != nil {
		log.Fatalf("debconf communication failed: %v\n", err)
	}
}

type debconfCommunicator struct {
	writer io.WriteCloser
	reader *bufio.Reader
	err    error
}

func initDebconf() *debconfCommunicator {
	return &debconfCommunicator{
		reader: bufio.NewReader(os.Stdin),
		writer: os.Stdout,
	}
}

func (d *debconfCommunicator) tell(cmd string) {
	if d == nil || d.err != nil {
		return
	}
	if _, err := fmt.Fprintf(d.writer, cmd+"\n"); err != nil {
		d.err = fmt.Errorf("failed to write debconf command %q: %w", cmd, err)
		return
	}
	if _, err := d.reader.ReadString('\n'); err != nil {
		d.err = fmt.Errorf("failed to read debconf response: %w", err)
		return
	}
}

func (d *debconfCommunicator) stop() error {
	return d.err
}
