package main

import (
	"os"
	"os/exec"

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

// runNpmBuild runs npm build and streams logs into the "build" room
func runNpmBuild(server *socketio.Server) error {
	cmd := exec.Command("npm", "run", "build")
	if os.Getenv("RUNNING_IN_DOCKER") == "true" {
		cmd.Dir = "/app"
	}

	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
}
