package main

import (
	"context"
	"os"
	"os/signal"
	"strconv"
	"sync/atomic"
	"syscall"

	"tsne.dev/hopper/internal/cli"
	"tsne.dev/hopper/internal/log"
)

func main() {
	log.Init(os.Stdout, os.Stderr)

	sigch := make(chan os.Signal, 1)
	signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)

	ctx, cancel := context.WithCancelCause(context.Background())
	defer cancel(nil)

	var receivedSignal int64
	go func() {
		sig := (<-sigch).(syscall.Signal)
		atomic.StoreInt64(&receivedSignal, int64(sig))

		var signame string
		switch sig {
		case syscall.SIGINT:
			signame = "SIGINT"
		case syscall.SIGTERM:
			signame = "SIGTERM"
		default:
			signame = "signal " + strconv.Itoa(int(sig))
		}

		log.Print("received %s", signame)
		cancel(cli.CancellationError("operation aborted (" + signame + ")"))
	}()

	code := cli.Run(ctx, os.Args[1:])
	if sig := atomic.LoadInt64(&receivedSignal); sig != 0 {
		code = 128 + int(sig)
	}
	os.Exit(code)
}
