// Copyright 2021 The Erigon Authors
// This file is part of Erigon.
//
// Erigon is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Erigon 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Erigon. If not, see <http://www.gnu.org/licenses/>.

package common

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/anacrolix/envpprof"
	"github.com/felixge/fgprof"

	"github.com/erigontech/erigon/common/log/v3"
)

// Runs main with envpprof and fgprof. You probably only want to do this at the main-level as the
// profilers are global.
func WithProfilersMain(main func()) {
	defer envpprof.Stop()
	http.DefaultServeMux.Handle("/debug/fgprof", fgprof.Handler())
	main()
}

func RootContext() (context.Context, context.CancelFunc) {
	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		defer cancel()

		ch := make(chan os.Signal, 1)
		defer close(ch)

		signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
		defer signal.Stop(ch)

		select {
		case sig := <-ch:
			log.Info("Got interrupt, shutting down...", "sig", sig)
		case <-ctx.Done():
		}
	}()
	return ctx, cancel
}

func CliString2Array(input string) []string {
	l := strings.Split(input, ",")
	res := make([]string, 0, len(l))
	for _, r := range l {
		if r = strings.TrimSpace(r); r != "" {
			res = append(res, r)
		}
	}
	return res
}
