// This code is a Flask web application that manages Windows services.
// The equivalent code is implemented using the Gin framework in Go.

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"

	"github.com/gin-gonic/gin"
)

var config map[string]interface{}
var logger = log.Default()

func getServiceHome(method string, apiHead string) string {
	text := fmt.Sprintf(`
		<p>执行完成，请返回</p>
        <form method="%s" action="%s">
            <input type="submit" value="返回">
        </form>
	`, method, apiHead)
	return text
}

func getServiceRestartList(method string, apiHead string) string {
	text := ""
	if restartServices, ok := config["restart_service"].([]interface{}); ok {
		for _, service := range restartServices {
			if serviceStr, valid := service.(string); valid {
				text += fmt.Sprintf(`
                <form method="%s" action="%s%s">
                <input type="submit" value="重启%s服务">
                </form>`, method, apiHead, serviceStr, serviceStr)
			}
		}
	}
	return text
}

func getServiceStopList(method string, apiHead string) string {
	text := ""
	if stopServices, ok := config["stop_service"].([]interface{}); ok {
		for _, service := range stopServices {
			if serviceStr, valid := service.(string); valid {
				text += fmt.Sprintf(`
                <form method="%s" action="%s%s">
                <input type="submit" value="停止%s服务">
                </form>`, method, apiHead, serviceStr, serviceStr)
			}
		}
	}
	return text
}

func main() {
	defConfig := map[string]interface{}{
		"host":            "0.0.0.0",
		"port":            5000,
		"restart_service": []interface{}{"demo"},
		"stop_service":    []interface{}{"demo"},
	}

	configPath := "config.json"
	if len(os.Args) > 1 {
		configPath = os.Args[1]
	}

	config = defConfig
	file, err := os.Open(configPath)
	if err == nil {
		defer file.Close()
		if err := json.NewDecoder(file).Decode(&config); err != nil {
			logger.Println("Error loading config:", err)
		} else {
			logger.Println("配置:", config)
		}
	}

	router := gin.Default()

	router.GET("/", func(c *gin.Context) {
		text := getServiceRestartList("POST", "/service/restart/")
		text += getServiceStopList("POST", "/service/stop/")
		c.Header("Content-Type", "text/html; charset=utf-8")
		c.Data(http.StatusOK, "text/html", []byte(text))
	})

	router.GET("/service/", func(c *gin.Context) {
		text := getServiceRestartList("POST", "/service/restart/")
		text += getServiceStopList("POST", "/service/stop/")
		c.Header("Content-Type", "text/html; charset=utf-8")
		c.Data(http.StatusOK, "text/html", []byte(text))
	})

	router.POST("/service/restart/:serviceName", func(c *gin.Context) {
		serviceName := c.Param("serviceName")
		exec.Command("sc", "stop", serviceName).Run()  // Assuming service can be stopped via 'sc'
		exec.Command("sc", "start", serviceName).Run() // Assuming service can be started via 'sc'
		text := getServiceHome("GET", "/service/")
		c.Header("Content-Type", "text/html; charset=utf-8")
		c.Data(http.StatusOK, "text/html", []byte(text))
	})

	router.POST("/service/stop/:serviceName", func(c *gin.Context) {
		serviceName := c.Param("serviceName")
		exec.Command("sc", "stop", serviceName).Run() // Assuming service can be stopped via 'sc'
		text := getServiceHome("GET", "/service/")
		c.Header("Content-Type", "text/html; charset=utf-8")
		c.Data(http.StatusOK, "text/html", []byte(text))
	})

	router.POST("/service/start/:serviceName", func(c *gin.Context) {
		serviceName := c.Param("serviceName")
		exec.Command("sc", "start", serviceName).Run() // Assuming service can be started via 'sc'
		text := getServiceHome("GET", "/service/")
		c.Header("Content-Type", "text/html; charset=utf-8")
		c.Data(http.StatusOK, "text/html", []byte(text))
	})

	router.Run(fmt.Sprintf("%s:%.0f", config["host"], config["port"]))
}
