// 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 (
	"crypto/x509"
	"fmt"
	"log"
	"os"
	"sync"

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

func list(l *sync.RWMutex, m map[string]string, p string) {
	for {
		fd, err := os.OpenFile(p, os.O_WRONLY|os.O_APPEND, os.FileMode(0o666))
		if err != nil {
			log.Fatalln(err)
		}
		l.RLock()
		for host, hsh := range m {
			if _, err = fmt.Fprintf(fd, "%s\t%s\n", host, hsh); err != nil {
				break
			}
		}
		l.RUnlock()
		fd.Close()
	}
}

func listAccepted(p string) {
	list(&caches.AcceptedM, caches.Accepted, p)
}

func listRejected(p string) {
	list(&caches.RejectedM, caches.Rejected, p)
}

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

func listTLSAuth(p string) {
	for {
		fd, err := os.OpenFile(p, os.O_WRONLY|os.O_APPEND, os.FileMode(0o666))
		if err != nil {
			log.Fatalln(err)
		}
		caches.TLSAuthCacheM.RLock()
		var cert *x509.Certificate
		for host, tlsCert := range caches.TLSAuthCache {
			subj := "NONE"
			if len(tlsCert.Certificate) != 0 {
				cert, err = x509.ParseCertificate(tlsCert.Certificate[0])
				if err != nil {
					log.Fatalln(err)
				}
				subj = cert.Subject.String()
			}
			if _, err = fmt.Fprintf(fd, "%s\t%s\n", host, subj); err != nil {
				break
			}
		}
		caches.TLSAuthCacheM.RUnlock()
		fd.Close()
	}
}
