package main

import (
	"bufio"
	"errors"
	"fmt"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"

	"jobarranger2/src/libs/golibs/forker"
)

func main() {
	pid := os.Getpid()
	fmt.Printf("PID: %d\n", pid)

	// Read execpath
	var execPath string
	fmt.Print("Enter executable path: ")
	reader := bufio.NewReader(os.Stdin)
	execPath, _ = reader.ReadString('\n')
	execPath = strings.TrimSpace(execPath) // remove newline

	// Read parameters
	var params []string

	fmt.Println("Enter parameters one per line. Empty line to finish.")
	for {
		fmt.Print("> ")
		line, _ := reader.ReadString('\n')
		line = strings.TrimSpace(line)
		if line == "" {
			break
		}
		params = append(params, line)
	}

	fmt.Printf("Collected parameters: %#v\n", params)

	fileName := getBasenameWithoutExt(execPath)
	dirPath := filepath.Dir(execPath)

	stdoutPath := filepath.Join(dirPath, fileName) + ".stdout"
	stderrPath := filepath.Join(dirPath, fileName) + ".stderr"
	retPath := filepath.Join(dirPath, fileName) + ".ret"
	execFilePath := "C:\\program files\\exec"
	jobRunFilePath := "C:\\program files\\jobrun"
	ServerIPsFilePath := "C:\\program files\\serverips"

	// Main Usage start here
	procForker := forker.New(forker.ProcessData{
		ExecPath: execPath,
		ExecParams: []string{
			"-exec-file-path", execFilePath,
			"-job-run-file-path", jobRunFilePath,
			"-server-ips-path", ServerIPsFilePath,
		}, // Optional - Add if there is any parameter for the executable
		StdoutPath: stdoutPath,
		StderrPath: stderrPath,
		RetPath:    retPath,

		// Username: "datuser",				Optional
		// Password: "123@dirace",			Optional
		// Domain: "DAT",					Optional - Only for windows

		Detached: true,
	})

	cmd, err := procForker.StartNewProcess()
	if err != nil {
		if errors.Is(err, forker.ErrExecCheck) {
			log.Print(err.Error())
		}
		log.Fatalf("failed to start process: %v", err)
	}

	fmt.Printf("PID: %d\n", cmd.Process.Pid)

	// Wait until the process finished
	err = cmd.Wait()
	if err != nil {
		log.Fatalf("failed to wait for process: %v", err)
	}

}

func getBasenameWithoutExt(fullPath string) string {
	// Normalize path separators first
	fullPath = filepath.ToSlash(fullPath)

	// Get the base filename with extension
	filename := path.Base(fullPath)

	// Remove the extension
	return filename[:len(filename)-len(path.Ext(filename))]
}
