package main

import (
	"fmt"
	"os"

	flag "github.com/spf13/pflag"
)

func main() {
	var c = readCfg("config.yml")

	//start command config flags
	startCmd := flag.NewFlagSet("start", flag.ExitOnError)
	startScreen := startCmd.BoolP("screen", "s", c.Factoryman.UseScreen, "Start server in screen session")
	startServerExec := startCmd.StringP("exec", "e", c.Server.ServExec, "Path to server executable")
	startSettings := startCmd.StringP("config", "c", c.Server.ServCfg, "Server config json")
	startPort := startCmd.IntP("port", "p", c.Server.ServPort, "Port to start server on")
	startScrName := startCmd.StringP("name", "n", c.Factoryman.ScreenName, "Name for screen session")
	startWorld := startCmd.StringP("world", "w", c.Server.WorldFile, "World file")

	// stop command config flags
	stopCmd := flag.NewFlagSet("stop", flag.ExitOnError)
	stopScrName := stopCmd.StringP("name", "n", c.Factoryman.ScreenName, "Screen session name")

	// download command flags
	downloadCmd := flag.NewFlagSet("download", flag.ExitOnError)
	downloadSrvLoc := downloadCmd.StringP("path", "d", c.Server.ServDir, "Server Directory path")
	downloadAPIKey := downloadCmd.StringP("token", "t", c.Factoryman.ApiToken, "API token")
	downloadUserName := downloadCmd.StringP("username", "u", c.Factoryman.UserName, "Factorio username")

	// backup command flags
	backupCmd := flag.NewFlagSet("backup", flag.ExitOnError)
	backupDir := backupCmd.StringP("path", "d", c.Factoryman.BackupDir, "Path to backup directory")

	if len(os.Args) < 2 {
		fmt.Println("Expected subcommand. \n\tex.) start, stop, download")
		os.Exit(1)
	}

	switch os.Args[1] {
	case "start":
		fmt.Println("starting server")

		startCmd.Parse(os.Args[2:])
		//map user input settings to config struct
		c.Factoryman.UseScreen = *startScreen
		c.Server.ServExec = *startServerExec
		c.Server.ServCfg = *startSettings
		c.Server.ServPort = *startPort
		c.Factoryman.ScreenName = *startScrName
		c.Server.WorldFile = *startWorld

		startStopServer("start", c)
	case "stop":
		fmt.Println("stopping server")

		stopCmd.Parse(os.Args[2:])
		c.Factoryman.ScreenName = *stopScrName

		startStopServer("stop", c)
	case "download":
		downloadCmd.Parse(os.Args[2:])
		c.Server.ServDir = *downloadSrvLoc
		c.Factoryman.ApiToken = *downloadAPIKey
		c.Factoryman.UserName = *downloadUserName

		switch os.Args[2] {
		case "mods":
			fmt.Println("Processing mod-list.json")
			downloadMods(c)
		case "server":
			fmt.Println("starting download")
			downloadHeadless(c)
		default:
			fmt.Println("mods or server")
			os.Exit(1)
		}
	case "backup":
		backupCmd.Parse(os.Args[2:])
		c.Factoryman.BackupDir = *backupDir

		switch os.Args[2] {
		case "saves":
			backUp("saves", c)
		case "full":
			backUp("full", c)
		default:
			fmt.Println("saves or full")
			os.Exit(1)
		}
	case "dev":
		fmt.Println("=)")
	default:
		flag.Usage()
		os.Exit(1)
	}
}
