package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	"github.com/mattn/go-xmpp"
	"gopkg.in/ini.v1"
)

type cfgStruct struct {
	srv   string
	usr   string
	pwd   string
	dest  string
	notls bool
}

func serverName(host string) string {
	return strings.Split(host, ":")[0]
}

func cfgRead(CfgFile string) cfgStruct {
	dir, dir_err := filepath.Abs(filepath.Dir(os.Args[0]))
	var ret cfgStruct
	if dir_err != nil {
		fmt.Printf("fail to open dir: %v", dir_err)
	}
	cfg, cfg_err := ini.Load(path.Join(dir, CfgFile))
	if cfg_err != nil {
		fmt.Printf("Fail to read file: %v", cfg_err)
		os.Exit(1)
	}
	cfg_notls, _ := cfg.Section("").Key("notls").Bool()
	ret.srv = cfg.Section("").Key("server").String()
	ret.usr = cfg.Section("").Key("username").String()
	ret.pwd = cfg.Section("").Key("password").String()
	ret.notls = cfg_notls
	ret.dest = cfg.Section("").Key("dest").String()
	return ret
}

func jabberClient(cfg cfgStruct) *xmpp.Client {
	var server = flag.String("server", cfg.srv, "server")
	var username = flag.String("username", cfg.usr, "username")
	var password = flag.String("password", cfg.pwd, "password")
	var status = flag.String("status", "xa", "status")
	var statusMessage = flag.String("status-msg", "", "")
	var notls = flag.Bool("notls", cfg.notls, "No TLS")
	var debug = flag.Bool("debug", false, "debug output")
	var session = flag.Bool("session", false, "use server session")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: example [options]\n")
		flag.PrintDefaults()
		os.Exit(2)
	}
	flag.Parse()
	if *username == "" || *password == "" {
		if *debug && *username == "" && *password == "" {
			fmt.Fprintf(os.Stderr, "no username or password were given; attempting ANONYMOUS auth\n")
		} else if *username != "" || *password != "" {
			flag.Usage()
		}
	}

	if !*notls {
		xmpp.DefaultConfig = tls.Config{
			ServerName:         serverName(*server),
			InsecureSkipVerify: false,
		}
	}

	var talk *xmpp.Client
	var err error
	options := xmpp.Options{Host: *server,
		User:          *username,
		Password:      *password,
		NoTLS:         *notls,
		Debug:         *debug,
		Session:       *session,
		Status:        *status,
		StatusMessage: *statusMessage,
	}

	talk, err = options.NewClient()
	if err != nil {
		fmt.Println(err)
	}
	return talk
}

func jabberReader(talk *xmpp.Client) {
	for {
		_, err := talk.Recv()
		if err != nil {
			fmt.Println(err)
		}
	}
}

func main() {
	cfg := cfgRead("goxmppalert.ini")
	var send_remote string
	var send_text string
	if len(os.Args) == 3 {
		send_remote = os.Args[1]
		send_text = os.Args[2]
	} else {
		send_remote = cfg.dest
		send_text = os.Args[1]
	}
	talk := jabberClient(cfg)
	go jabberReader(talk)
	go talk.Send(xmpp.Chat{Remote: send_remote, Type: "chat", Text: send_text})
	time.Sleep(1 * time.Second)
}
