package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strconv"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/sevlyar/go-daemon"
)

func main() {
	// Find program's path/directory.
	var pathExecutable string
	pathExecutable, _ = os.Executable()
	// Getting the directory path/name
	var dirPathExecutable string = filepath.Dir(pathExecutable)
	os.Chdir(dirPathExecutable)

	var background bool
	var port int
	var bind string
	flag.BoolVar(&background, "d", false, "Run in background detached")
	flag.IntVar(&port, "p", 8000, "Port to listen on")
	flag.StringVar(&bind, "b", "0.0.0.0", "Interface to bind to")
	flag.Parse()

	var cntxt *daemon.Context = &daemon.Context{
		PidFileName: "roku.pid",
		PidFilePerm: 0644,
		LogFileName: "roku.log",
		LogFilePerm: 0640,
		WorkDir:     "./",
		Umask:       027,
		Args:        []string{},
	}

	var d *os.Process
	var err error

	if background {
		d, err = cntxt.Reborn()

		if err != nil {
			log.Fatal("Unable to run:", err)
		}
		if d != nil {
			return
		}
		defer cntxt.Release()

		log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
		log.Println("daemon started")
		defer os.Remove("roku.pid")
	} else {
		// set up logging

		// Write log.print ect into a file
		var logfilename string = "roku.log"
		var logf *os.File

		logf, err = os.OpenFile(logfilename, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
		if err != nil {
			log.Panicf("Error creating log file %s: %v", logfilename, err)
		}
		log.SetOutput(logf)
		log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	}

	var web WebServer = WebServer{}
	web.Init("192.168.254.75", bind, strconv.Itoa(port))

	var e *echo.Echo = echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Static("static"))
	e.Renderer = NewRenderer("./templates/*.html", true)

	e.GET("/", web.homepage)
	e.GET("/tv/:cmd", web.tvcmd)
	e.GET("/connect", web.connectpage)
	e.GET("/con/:cmd", web.connector)
	e.GET("/conn_refresh", web.con_refresh)

	e.Logger.Fatal(e.Start(fmt.Sprintf("%s:%s", web.Host, web.Port)))
}
