// 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 tofuproxy

import (
	"net"
	"sync"
	"time"
)

type SingleConn struct {
	conn net.Conn
	ln   *SingleListener
	once sync.Once
}

func (conn *SingleConn) Read(b []byte) (int, error) { return conn.conn.Read(b) }

func (conn *SingleConn) Write(b []byte) (int, error) { return conn.conn.Write(b) }

func (conn *SingleConn) Close() error {
	conn.once.Do(conn.ln.Unlock)
	return conn.conn.Close()
}

func (conn *SingleConn) LocalAddr() net.Addr { return conn.conn.LocalAddr() }

func (conn *SingleConn) RemoteAddr() net.Addr { return conn.conn.RemoteAddr() }

func (conn *SingleConn) SetDeadline(t time.Time) error { return conn.conn.SetDeadline(t) }

func (conn *SingleConn) SetReadDeadline(t time.Time) error { return conn.conn.SetReadDeadline(t) }

func (conn *SingleConn) SetWriteDeadline(t time.Time) error { return conn.conn.SetWriteDeadline(t) }

type AlreadyAccepted struct{}

func (err AlreadyAccepted) Error() string { return "already accepted" }

type SingleListener struct {
	conn     net.Conn
	accepted bool
	sync.Mutex
}

func (ln *SingleListener) Accept() (net.Conn, error) {
	ln.Lock()
	if ln.accepted {
		return nil, AlreadyAccepted{}
	}
	ln.accepted = true
	return &SingleConn{conn: ln.conn, ln: ln}, nil
}

func (ln *SingleListener) Close() error { return nil }

func (ln *SingleListener) Addr() net.Addr { return ln.conn.LocalAddr() }
