package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/user"
	"syno-common/server/sso"
	"syno-common/server/utils"
)

func main() {
	// Todo:
	// fix-up error handling with correct http responses (add --debug flag?/Synology's notifications?)
	// worry about csrf
	//dev = flag.Bool("dev", false, "Turns Authentication checks off")
	//flag.Parse()

	var logF *os.File
	var err error

	curDir := utils.GetCurDir()
	logF, err = os.OpenFile(fmt.Sprintf("%v/commontools.log", curDir), os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
	if err == nil {
		defer func() {
			logF.Close()
		}()
		log.SetOutput(logF)
	}
	u, _ := user.Current()
	if u != nil {
		log.Println("user", u)
	}

	synoResp := sso.SynoAuth()

	if !synoResp.Ok {
		synoResp.PrintNoData()
		os.Exit(0)
	}

	userData := synoResp.Data
	resp := sso.LoginByAccount(userData.User)
	if !resp.Ok {
		r := sso.UnauthorisedResp()
		r.PrintNoData()
		os.Exit(0)
	}
	synoResp.PrintNoData()
	data := resp.Data
	jsonData, _ := json.Marshal(data)
	fmt.Print(string(jsonData))
}
