package main

import (
	"os"
	"os/exec"
	"qvm/internal/config"
	"qvm/internal/logging"
	"qvm/internal/vm"
	"qvm/internal/workspace"
	"strconv"

	"github.com/spf13/cobra"
)

var (
	sshCommand string
)

var sshCmd = &cobra.Command{
	Use:   "ssh",
	Short: "SSH into the VM",
	Long: `Open an SSH session to the running VM.

By default opens an interactive shell.
Use -c to run a single command.`,
	Run: func(cmd *cobra.Command, args []string) {
		if !vm.IsRunning() {
			logging.Info("VM is not running, starting it...")
			cfg, err := config.Load()
			if err != nil {
				logging.Error(err.Error())
				os.Exit(1)
			}

			regResult := workspace.Load(config.WorkspacesFile)
			if regResult.IsError() {
				logging.Error(regResult.Error().Error())
				os.Exit(1)
			}
			reg := regResult.MustGet()

			startResult := vm.Start(cfg, reg)
			if startResult.IsError() {
				logging.Error(startResult.Error().Error())
				os.Exit(1)
			}
		}

		statusResult := vm.Status()
		if statusResult.IsError() {
			logging.Error(statusResult.Error().Error())
			os.Exit(1)
		}
		status := statusResult.MustGet()

		sshArgs := []string{
			"-p", "root",
			"ssh",
			"-o", "StrictHostKeyChecking=no",
			"-o", "UserKnownHostsFile=/dev/null",
			"-o", "LogLevel=ERROR",
			"-p", strconv.Itoa(status.SSHPort),
			"root@localhost",
		}

		if sshCommand != "" {
			sshArgs = append(sshArgs, sshCommand)
		}

		sshpassCmd := exec.Command("sshpass", sshArgs...)
		sshpassCmd.Stdin = os.Stdin
		sshpassCmd.Stdout = os.Stdout
		sshpassCmd.Stderr = os.Stderr

		if err := sshpassCmd.Run(); err != nil {
			if exitErr, ok := err.(*exec.ExitError); ok {
				os.Exit(exitErr.ExitCode())
			}
			os.Exit(1)
		}
	},
}

func init() {
	sshCmd.Flags().StringVarP(&sshCommand, "command", "c", "", "Command to run instead of interactive shell")
}
