package main

import (
	"context"
	"flag"
	"fmt"
	"os"

	"github.com/masterzen/winrm"
)

var (
	hostnameFlag   = flag.String("hostname", "", "Public IPv4 address or Public IPv4 DNS of your windows server.")
	portFlag       = flag.Int("port", 5985, "port of the remote machine.")
	usernameFlag   = flag.String("username", "", "username of the remote machine.")
	passwordFlag   = flag.String("password", "", "password of the remote machine.")
	cmdFlag        = flag.String("cmd", " ", "commands that will run on the remote machine.")
)

func getEmptyManFlag() string {
	if *hostnameFlag == "" {
		return "hostname"
	}
	if *usernameFlag == "" {
		return "username"
	}
	if *passwordFlag == "" {
		return "password"
	}
	return ""
}

func main() {
	// get flags' values
	flag.Parse()

	// check mandatory flags
	if emptyFlag := getEmptyManFlag(); emptyFlag != "" {
		fmt.Printf("Error: -%s is mandatory.\n", emptyFlag)
		os.Exit(1)
	}

	// // create stdout file
	// stdOutFile, err := os.Create(*stdOut)
	// if err != nil {
	// 	fmt.Printf("In %s(), Error: %s.\n", "Create", err.Error())
	// 	os.Exit(1)
	// }

	// // create std error file
	// stdErrFile, err := os.Create(*stdErr)
	// if err != nil {
	// 	fmt.Printf("In %s(), Error: %s.\n", "Create", err.Error())
	// 	os.Exit(1)
	// }

	// create context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	endpoint := winrm.NewEndpoint(*hostnameFlag, *portFlag, false, false, nil, nil, nil, 0)
	client, err := winrm.NewClient(endpoint, *usernameFlag, *passwordFlag)
	if err != nil {
		fmt.Printf("In %s(), Error: %s.\n", "NewClient", err.Error())
		os.Exit(1)
	}

	i, err := client.RunWithContext(ctx, *cmdFlag, os.Stdout, os.Stderr)
	if err != nil {
		fmt.Printf("In %s(), Error: %s.\n", "RunWithContext", err.Error())
		os.Exit(1)
	}
	os.Exit(i)
}
