package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"sync"
	"time"
)

func main() {
	var (
		fifo  string
		delay time.Duration
	)
	flag.StringVar(&fifo, "fifo", fifo, "Name of FIFO")
	flag.DurationVar(&delay, "delay", 0, "Delay before reading")
	flag.Parse()

	var (
		r io.ReadCloser
		w io.WriteCloser
	)

	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()

		var err error
		w, err = os.OpenFile(fifo, os.O_WRONLY, 0)
		if err != nil {
			log.Fatalf("write open err=%q", err)
		}
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()

		var err error
		r, err = os.OpenFile(fifo, os.O_RDONLY, 0)
		if err != nil {
			log.Fatalf("read open err=%q", err)
		}
	}()

	wg.Wait()

	defer func(c io.Closer) {
		err := c.Close()
		if err != nil {
			log.Printf("close err=%q", err)
		}
	}(w)

	defer func(c io.Closer) {
		err := c.Close()
		if err != nil {
			log.Printf("close err=%q", err)
		}
	}(r)

	time.Sleep(delay)

	// go func() {
	// 	_, err := io.Copy(os.Stdout, r)
	// 	if err != nil {
	// 		log.Printf("copy err=%q", err)
	// 	}
	// }()

	fmt.Fprintf(w, "hello world\n")

	time.Sleep(delay)
}
