package main

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

	socketio "github.com/googollee/go-socket.io"
)

// ---- Run npm build ----
func runNpmV2Build(server *socketio.Server) error {
	cmd := exec.Command("npm", "run", "newBuild")
	if os.Getenv("RUNNING_IN_DOCKER") == "true" {
		cmd.Dir = "/app"
	} else {
		// Go three directories up from the current working directory
		cwd, err := os.Getwd()
		if err != nil {
			return err
		}
		dir := filepath.Join(cwd, "..", "lstV2")
		cmd.Dir = dir
	}

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		return err
	}

	if err := cmd.Start(); err != nil {
		return err
	}

	// Launch goroutines to forward output
	go streamOutput(stdout, server, "build")
	go streamOutput(stderr, server, "build")

	return cmd.Wait() // Wait until process finishes

}
