package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"time"

	"github.com/go-ping/ping"
)

func main() {
	if err := run(); err != nil {
		panic(err)
	}
}

func run() error {
	fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
	domain := fs.String("d", "www.google.com", "address to ping")
	c := fs.Int("c", 0, "limit pings")
	o := fs.String("o", "csv", "output format (csv, json)")
	if err := fs.Parse(os.Args[1:]); err != nil {
		return err
	}

	pinger, err := ping.NewPinger(*domain)
	if err != nil {
		return err
	}
	pinger.Count = *c
	pinger.SetPrivileged(true)

	switch *o {
	case "csv":
		fmt.Printf("ts,n,ok_pct,max,avg,stddev\n")
	case "json":
	default:
		panic(*o)
	}
	pinger.OnRecv = func(*ping.Packet) {
		stat := pinger.Statistics()
		switch *o {
		case "csv":
			fmt.Printf("%s,%d,%.0f%%,%dms,%dms,%dms\n",
				time.Now().UTC().Format("2006-01-02T15:04:05Z"),
				stat.PacketsRecv,
				stat.PacketLoss,
				stat.MaxRtt.Milliseconds(),
				stat.AvgRtt.Milliseconds(),
				stat.StdDevRtt.Milliseconds(),
			)
		case "json":
			b, _ := json.Marshal(map[string]any{
				"ts":      time.Now().UTC().Format("2006-01-02T15:04:05Z"),
				"n":       stat.PacketsRecv,
				"bad_pct": stat.PacketLoss,
				"max":     stat.MaxRtt.Milliseconds(),
				"avg":     stat.AvgRtt.Milliseconds(),
				"stddev":  stat.StdDevRtt.Milliseconds(),
			})
			fmt.Printf("%s\n", b)
		}
	}

	if err := pinger.Run(); err != nil {
		return err
	}

	return nil
}
