package cmd

import (
	"context"
	"log"
	"os"
	"os/signal"
	"sync"
	"syscall"

	"github.com/spf13/cobra"
)

// localrunCmd represents the localrun command
var localrunCmd = &cobra.Command{
	Use:   "localrun",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {

		folderPath := "bin"

		ctx, cancel := context.WithCancel(context.Background())
		wg := &sync.WaitGroup{}

		// Handle Ctrl+C (SIGINT) and other termination signals
		signalChannel := make(chan os.Signal, 1)
		signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)

		if findCaddyRuntime(folderPath) == "" {
			log.Println("Caddy runtime not found")
			downloadLatestCaddy(folderPath)
		}

		// Start the goroutines to run programs
		walkFolder(folderPath, ctx, wg)

		go func() {
			// Wait for a termination signal (like Ctrl+C)
			<-signalChannel

			log.Println("Received termination signal. Stopping all processes...")

			// Call cancel to stop all the processes gracefully
			cancel()

			// Force kill all processes
			stopAllProcesses()

			// Exit the program
			os.Exit(0)
		}()

		// Wait for all processes to finish
		wg.Wait()

		log.Println("All processes stopped.")

	},
}

func init() {
	rootCmd.AddCommand(localrunCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// localrunCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// localrunCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
