package main

import (
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"time"
)

/*
	ArozOS Launcher
	For auto update and future extension purpose

	Author: tobychui

*/

const (
	launcherVersion = "1.0"
)

var (
	arozosRunning bool = false
)

func main() {
	//Print basic information
	fmt.Println("[LAUNCHER] ArozOS Launcher ver " + launcherVersion)
	binaryName := autoDetectExecutable()
	fmt.Println("[LAUNCHER] Choosing binary executable: " + binaryName)

	//Check if updates exists. If yes, overwrite it
	updateIfExists(binaryName)

	//Register the binary start path
	cmd := exec.Command(binaryName, os.Args[1:]...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	//Register the http server to notify ArozOS there is a launcher will handle the update
	go func() {
		http.HandleFunc("/chk", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("LauncherA v" + launcherVersion))
			fmt.Println("[LAUNCHER] CHK RECV - DONE")
		})

		http.ListenAndServe("127.0.0.1:25576", nil)
	}()

	retryCounter := 0
	//Start the cmd
	for {
		startTime := time.Now().Unix()
		cmd.Run()
		endTime := time.Now().Unix()
		if endTime-startTime < 3 {
			//Less than 3 seconds, shd be crashed. Add to retry counter
			fmt.Println("[LAUNCHER] ArozOS Crashed. Restarting in 3 seconds... ")
			retryCounter++
		} else {
			fmt.Println("[LAUNCHER] ArozOS Exited. Restarting in 3 seconds... ")
		}

		time.Sleep(3 * time.Second)

		if retryCounter > 10 {
			//Restore from old version of the binary
			restoreOldArozOS()
			retryCounter = 0
		} else {
			updateIfExists(binaryName)
		}

		//Rebuild the start paramters
		cmd = exec.Command(binaryName, os.Args[1:]...)
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr

	}

}
