package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"kas/conn"
	"kas/conn/http"
	"kas/conn/twilio"
	"kas/conn/xmpp"

	"gopkg.in/yaml.v2"
)

type Config struct {
	Connections conn.Config `yaml:"conns"`
	HTTP        string      `yaml:"http"`
}

func loadConfig(path string) (*Config, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, fmt.Errorf("kas: missing config file '%s'", path)
		}
		return nil, err
	}

	cfg := &Config{}
	err = yaml.Unmarshal(data, cfg)
	return cfg, err
}

func main() {
	configPath := "kas.yaml"
	flag.StringVar(&configPath, "f", configPath, "`path` to config file")
	flag.Parse()

	cfg, err := loadConfig(configPath)
	if err != nil {
		log.Fatal(err)
	}

	if cfg.Connections.XMPP != nil {
		if err = xmpp.Start(cfg.Connections.XMPP); err != nil {
			log.Fatal(err)
		}
	}

	if cfg.Connections.Twilio != nil {
		if err = twilio.SetConfig(cfg.Connections.Twilio); err != nil {
			log.Fatal(err)
		} else {
			twilio.Start()
		}
	}

	if cfg.HTTP != "" {
		http.Start(cfg.HTTP)
	}

	waitForControlC()
}