package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"

	cp "github.com/otiai10/copy"
)

/*
	ArozOS Launcher
	For auto update and future extension purpose

	Author: tobychui

*/

const (
	launcherVersion = "1.0"
)

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
	if fileExists("./updates") && fileExists("./updates/web/") && fileExists("./updates/system") {
		//All component exists. Update it
		newArozBinary, err := getUpdateBinaryFilename()
		if err != nil {
			fmt.Println("[LAUNCHER] Unable to access update files: ", err.Error())
		} else {
			//Binary file got. Update it
			//Backup the current executables and system files
			fmt.Println("[LAUNCHER] Starting system backup process (to ./arozos.old)")
			os.MkdirAll("./arozos.old", 0775)
			copy(binaryName, filepath.Join("./arozos.old", filepath.Base(binaryName)))
			cp.Copy("./system", "./arozos.old/system/")
			cp.Copy("./web", "./arozos.old/web/")

			//Success. Continue binary replacement
			fmt.Println("[LAUNCHER] Copying updates to runtime environment")
			copy(newArozBinary, binaryName)
			cp.Copy("./updates/system", "./system/")
			cp.Copy("./updates/web", "./web/")

			fmt.Println("[LAUNCHER] Update Completed. Removing the update files")
			os.RemoveAll("./updates/")
		}

	} else if fileExists("./updates") && (!fileExists("./updates/web/") || !fileExists("./updates/system")) {
		//Update folder exists but some components is broken
		fmt.Println("[LAUNCHER] Detected damaged / incomplete update package. Skipping update process")
	}

	cmd := exec.Command(binaryName, os.Args[1:]...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Run()

}
