// tofuproxy -- flexible HTTP/HTTPS proxy, TLS terminator, X.509 TOFU
//              manager, WARC/geminispace browser
// Copyright (C) 2021-2026 Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package fifos

import (
	"fmt"
	"log"
	"os"
	"strings"

	"go.stargrave.org/tofuproxy/caches"
)

func listRestricted(p string) {
	for {
		fd, err := os.OpenFile(p, os.O_WRONLY|os.O_APPEND, os.FileMode(0o666))
		if err != nil {
			log.Fatalln(err)
		}
		caches.RestrictedM.RLock()
		for spki, hosts := range caches.Restricted {
			for _, host := range hosts {
				if _, err = fmt.Fprintf(fd, "%s\t%s\n", spki, host); err != nil {
					break
				}
			}
		}
		caches.RestrictedM.RUnlock()
		fd.Close()
	}
}

func addRestricted(p string) {
	for {
		neu := make(map[string][]string)
		for _, line := range readLinesFromFIFO(p) {
			cols := strings.Fields(line)
			if len(cols) != 2 {
				continue
			}
			spki, host := cols[0], cols[1]
			log.Printf("%s: adding %s: %s\n", p, spki, host)
			neu[spki] = append(neu[spki], host)
		}
		caches.RestrictedM.Lock()
		for spki, hosts := range neu {
			caches.Restricted[spki] = append(caches.Restricted[spki], hosts...)
		}
		caches.RestrictedM.Unlock()
	}
}
