// 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")
	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(debconfCommand string) {
	if d == nil || d.err != nil {
		return
	}
	if _, err := fmt.Fprintf(d.writer, debconfCommand+"\n"); err != nil {
		d.err = err
		return
	}
	if _, err := d.reader.ReadString('\n'); err != nil {
		d.err = err
		return
	}
}

func (d *debconfCommunicator) stop() error {
	if d.err != nil {
		return d.err
	}
	return d.writer.Close()
}
