package main

import (
	"log"
	"os"
	"sync"
)

var config Config

const sockfile = "/tmp/gopaper.sock"

func main() {
	//TODO:kill existing processes

	log.SetFlags(log.LstdFlags | log.Lshortfile)

	err := config.load()
	logfile, err := openLogfile()
	if err != nil {
		log.Println("failed to load config", err)
		cleanExit(1)
	}
	log.SetOutput(logfile)
	log.SetFlags(log.LstdFlags | log.Lshortfile | log.Lmicroseconds)
	log.Println("Welcome to GoPaper!")

	var waitGroup sync.WaitGroup
	waitGroup.Add(1)
	slideshowDir := make(chan string)

	func() {
		defer func() {
			if r := recover(); r != nil {
				log.Println("Panic recovered at top level. Closing gracefully.", r)
				cleanExit(1)
			}
		}()
		go server(slideshowDir)
		go slideshow(slideshowDir)
	}()

	var dir string
	args := os.Args[1:]
	if len(args) > 0 {
		dir = args[0]
	} else {
		dir = config.Default
	}
	slideshowDir <- dir

	waitGroup.Wait()
}

func openLogfile() (*os.File, error) {
	//TODO: log rotation
	f, err := os.OpenFile(config.Cache+"/logfile", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		return nil, err
	}
	return f, nil
}
