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

import (
	"bufio"
	"compress/gzip"
	"fmt"
	"io"
	"log"
	"os"
)

type CountableReader struct {
	*bufio.Reader
	n int64
}

func (r *CountableReader) ReadByte() (b byte, err error) {
	b, err = r.Reader.ReadByte()
	if err == nil {
		r.n++
	}
	return b, err
}

func (r *CountableReader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	r.n += int64(n)
	return
}

func main() {
	log.SetFlags(log.Lshortfile)
	fdOff := os.NewFile(3, "fdOff")
	br := bufio.NewReader(os.Stdin)
	cr := &CountableReader{Reader: br}
	bw := bufio.NewWriter(os.Stdout)
	z, err := gzip.NewReader(cr)
	if err != nil {
		log.Fatalln(err)
	}
	z.Multistream(false)
	var offset, offsetPrev int64
	for {
		written, err := io.Copy(bw, z)
		if err != nil {
			log.Fatalln(err)
		}
		offset = cr.n
		if fdOff != nil {
			fmt.Fprintf(fdOff, "%d\t%d\n", offset-offsetPrev, written)
		}
		offsetPrev = offset
		err = z.Reset(cr)
		if err != nil {
			if err == io.EOF {
				break
			}
			log.Fatalln(err)
		}
		z.Multistream(false)
	}
}
