package main

import (
	"converge/pkg/iowrappers"
	"converge/pkg/websocketutil"
	"crypto/tls"
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net"
	"net/http"
	"os"
	"time"
)

func closeConnection(conn net.Conn) {
	if tcpConn, ok := conn.(*net.TCPConn); ok {
		tcpConn.SetLinger(0)
	}
	_ = conn.Close()
}

type Stdio struct{}

func (stdio Stdio) Read(b []byte) (n int, err error) {
	return os.Stdin.Read(b)
}
func (stdio Stdio) Write(b []byte) (n int, err error) {
	return os.Stdout.Write(b)
}

func main() {
	usage := "Usage: wsproxy [--insecure] ws[s]://<host>[:port]/client/<ID>\n\n" +
		"\n" +
		"Here <ID> is the rendez-vous id of a continuous integration job\n" +
		"\n" +
		"Use this in an ssh command like this: \n" +
		"\n" +
		"  ssh -oServerAliveInterval=10 -oProxyCommand='wsproxy ws[s]://<host>[:port]/client/<ID>' abc@localhost\n" +
		"\n" +
		"This latssh connect through wsproxy tocalhost\n"

	args := os.Args[1:]
	insecure := false

	if len(args) == 2 && args[0] == "--insecure" {
		insecure = true
		args = args[1:]
	}

	if len(args) != 1 {
		fmt.Fprintf(os.Stderr, usage)
		os.Exit(1)
	}

	wsURL := args[0]

	dialer := websocket.Dialer{
		Proxy:            http.ProxyFromEnvironment,
		HandshakeTimeout: 45 * time.Second,
	}
	if insecure {
		dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
	}
	_wsConn, _, err := dialer.Dial(wsURL, nil)
	if err != nil {
		panic(err)
	}
	if err != nil {
		log.Println("WebSocket connection error:", err)
		panic(err)
	}
	wsConn := websocketutil.NewWebSocketConn(_wsConn)
	defer wsConn.Close()

	iowrappers.SynchronizeStreams(wsConn, Stdio{})
}