package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	_ "net/http/pprof"
	"ordonnance/conf"
	"ordonnance/logger"
	"ordonnance/route"
	"os"
	"os/exec"
	"time"

	"github.com/urfave/cli"
)

var pidPath string
var pidName string

func main() {
	app := cli.NewApp()
	pidName = "./ordonnance"

	pidPath = pidName + ".pid"

	app.Name = "ordonnance"
	app.Author = "ordonnance authors"
	app.Version = "0.0.1"
	app.Copyright = "ordonnance authors reserved"
	app.Usage = "ordonnance start|stop|restart|{-d}"

	app.Commands = []cli.Command{
		cli.Command{
			Name: "start",
			Flags: []cli.Flag{
				&cli.BoolFlag{Name: "d", Usage: "run background"},
			},
			Aliases: []string{"start"},
			Action:  start,
		},
		cli.Command{
			Name:    "stop",
			Aliases: []string{"stop"},
			Action:  stop,
		},
		cli.Command{
			Name:    "restart",
			Aliases: []string{"restart"},
			Action:  restart,
		},
	}
	app.Run(os.Args)
}

func start(ctx *cli.Context) error {
	d := ctx.Bool("d")
	logger.Info("start_d ", d)
	if d {
		start := exec.Command(pidName, "start")
		start.Start()
		os.Exit(0)
	}
	doStart()
	return nil
}

// Start 启动
func doStart() {
	pid := fmt.Sprintf("%d", os.Getpid())
	if err := ioutil.WriteFile(pidPath, []byte(pid), 0666); err != nil {
		logger.Warn("start pid error ", pid)
		panic(err)
	}
	go func() {
		http.ListenAndServe(":6060", nil)
	}()

	addr := conf.GetPort()
	route.RunService(addr)
}

// Stop 停止
func stop(ctx *cli.Context) error {
	pid, _ := ioutil.ReadFile(pidPath)
	logger.Info("doStop ", ctx.String("stop"), string(pid))
	cmd := exec.Command("kill", "-9", string(pid))
	cmd.Start()
	if err := ioutil.WriteFile(pidPath, nil, 0666); err != nil {
		logger.Warnf("write pid error %v %v", string(pid), err.Error())
	}
	return nil
}

// Restart 重启
func restart(ctx *cli.Context) error {
	logger.Info("doRestart ", ctx.String("restart"))
	pid, _ := ioutil.ReadFile(pidPath)
	logger.Info("restarting..." + string(pid))
	stop := exec.Command("kill", "-9", string(pid))
	stop.Start()
	time.Sleep(5 * time.Second)
	start := exec.Command(pidName, "start")
	start.Start()
	return nil
}
