package main

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"strings"
	"syscall"

	"github.com/creack/pty"
)

func main() {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGTERM)

	var minram, maxram, args, stop string
	for _, e := range os.Environ() {
		pair := strings.SplitN(e, "=", 2)
		switch pair[0] {
		case "MIN_MEM":
			minram = "-Xms" + pair[1]
		case "MAX_MEM":
			maxram = "-Xmx" + pair[1]
		case "ARGS":
			args = pair[1]
		case "STOP":
			stop = pair[1]
		}
	}
	var cmd *exec.Cmd
	if args == "" {
		cmd = exec.Command("java", minram, maxram, "-jar", "server.jar")
	} else {
		cmd = exec.Command("java", minram, maxram, args, "-jar", "server.jar")
	}

	cmd.Dir = "/server"
	cmd.Stdout = os.Stdout
	tty, err := pty.Start(cmd)
	ln, _ := net.Listen("tcp", ":8081")

	if err != nil {
		panic(err)
	}

	defer func() {
		cmd.Process.Kill()
		cmd.Process.Wait()
		tty.Close()
		ln.Close()
	}()

	go func() {
		sig := <-sigs
		if sig == syscall.SIGTERM {
			fmt.Println("Stopping server")
			tty.WriteString(stop + "\n\r")
		}
	}()

	go func() {
		//accept connections from clients
		for {
			conn, err := ln.Accept()
			if err != nil {
				continue
			}
			go handleClient(conn, tty)
		}
	}()

	go func() {
		io.Copy(tty, os.Stdin)
	}()

	cmd.Wait()
	os.Exit(0)
}

func handleClient(conn net.Conn, tty *os.File) {
	defer conn.Close()
	cmd, _ := bufio.NewReader(conn).ReadString('\n')
	tty.Write([]byte(cmd))
}
