package main

import (
	"flag"
	"fmt"
	"os"

	log "github.com/sirupsen/logrus"
)

var (
	cfgFile  = flag.String("config", "", "config file")
	isDaemon = flag.Bool("daemon", false, "run as daemon")
	debug    = flag.Bool("debug", false, "log debug messages")
	quiet    = flag.Bool("quiet", false, "remove most log messages")
	logFile  = flag.String("logfile", "", "log file")
	cfg      *Config
)

func main() {
	flag.Parse()

	fmt.Printf("backup (%s)\n", version)

	if *debug {
		log.SetLevel(log.DebugLevel)
	}
	if *quiet {
		log.SetLevel(log.WarnLevel)
	}
	if *logFile != "" {
		if f, err := os.OpenFile(*logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644); err != nil {
			log.Printf("Cannot open logfile (%s)", err)
		} else {
			log.SetOutput(f)
			defer f.Close()
		}

	}
	log.SetReportCaller(true)

	if *cfgFile != "" {
		if c, err := LoadConfigFile(*cfgFile); err != nil {
			log.Printf("Cannot load config (%s)", err)
			os.Exit(1)
		} else {
			cfg = c
		}
	} else if c, err := LoadConfigFile("backup.json"); err == nil {
		cfg = c
	} else {
		cfg, _ = LoadConfigByte(sampleCfg)
	}

	if *isDaemon {
		if cfg.Admin == nil {
			cfg.Admin = NewAdmin()
		}
		if cfg.Admin.Secrets == nil {
			cfg.Admin.Secrets = NewSecrets()
		}
		if len(cfg.Admin.Users) == 0 {
			cfg.Admin.NewAdminUser()
		}
		cfg.Admin.Run()
	} else {
		cfg.Run()
		os.Exit(0)
	}

}
