package tools

import (
	"errors"
	"io"

	"os/exec"
	"strings"
	"velvettear/gosync/log"
	"velvettear/gosync/settings"
)

// exported function(s)
func TestConnection() error {
	if !settings.TargetIsRemote() {
		return nil
	}
	if len(settings.Password) == 0 {
		log.Warning("target is a remote host and no password is set, make sure passwordless login is configured")
	}
	var arguments []string
	if len(settings.Password) > 0 {
		arguments = append(arguments, "-p", settings.Password)
	}
	arguments = append(arguments, "ssh")
	target, _, _ := strings.Cut(settings.Target, ":")
	if len(settings.User) > 0 {
		target = settings.User + "@" + target
	}
	arguments = append(arguments, target, "'exit'")
	cmd := exec.Command("sshpass", arguments...)
	stdout, stdoutError := cmd.StdoutPipe()
	stderr, stderrError := cmd.StderrPipe()
	cmd.Start()
	if stdoutError != nil {
		return stdoutError
	}
	if stderrError != nil {
		return stderrError
	}
	_, stdoutError = io.ReadAll(stdout)
	if stdoutError != nil {
		return stdoutError
	}
	errorBytes, stderrError := io.ReadAll(stderr)
	if stderrError != nil {
		return stderrError
	}
	cmd.Wait()
	error := strings.TrimSpace(string(errorBytes))
	if len(error) > 0 {
		return errors.New(error)
	}
	return nil
}
