package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
)

func startStopServer(cmd string, con UsrConfig) {
	if hasInternet() != true {
		fmt.Printf("WARNING!\n\tNot connected to internet, LAN access only\n")
	}
	switch cmd {
	case "start":
		x := fmt.Sprintf("%s --port %d --server-settings %s --start-server %s", con.Server.ServExec, con.Server.ServPort, con.Server.ServCfg, con.Server.WorldFile)
		if con.Factoryman.UseScreen { // if screen enabled in config.yml
			fmt.Println("Starting factorio server in screen session")
			startScreenCmd := exec.Command("screen", "-dmS", con.Factoryman.ScreenName, "bash", "-c", x, "; exec sh")
			startScreenCmd.Stdout = os.Stdout
			startScreenCmd.Stderr = os.Stderr
			err := startScreenCmd.Run()
			if err != nil {
				log.Fatalf("Failed to start server: %s", err)
			}
		} else {
			startSrvCmd := exec.Command("bash", "-c", x)
			startSrvCmd.Stdout = os.Stdout
			startSrvCmd.Stderr = os.Stdout
			startSrvCmd.Stdin = os.Stdin
			err := startSrvCmd.Run()
			if err != nil {
				log.Fatalf("Failed to start server: %s", err)
			}
		}
	case "stop":
		quitServerCmd := exec.Command("screen", "-S", con.Factoryman.ScreenName, "-p", "0", "-X", "stuff", "/quit\n")
		err := quitServerCmd.Run()
		if err != nil {
			log.Fatalf("Command failed: %s, Error: %v", quitServerCmd.Args, err)
		} else {
			fmt.Println("Server Stopped")
		}
	}
}
