package goq

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"strconv"
)

// The default location of goq's config file
const (
	DefaultConfig = "/etc/goq/config.json"
)

// Config is the structure containing all goq configurations.
// Some options may be shared between goqd and the goq cli command
type Config struct {
	// ExecShell is the path to a shell used to execute the commandline.
	// The command is passed using the -c option, so make sure the used
	// shell supports this
	ExecShell            string      `json:"shell,omitempty"`
	JobDir               string      `json:"jobDir"`
	LogDir               string      `json:"logDir"`
	DefaultJobPermString string      `json:"defaultJobPermission"`
	DefaultJobPerm       os.FileMode `json:"-"`
	Workers              []Worker    `json:"worker"`
}

// ReadConfigFile reads and parses a config file located a filepath
// returnes the filled Config struct
func ReadConfigFile(filepath string) (*Config, error) {
	raw, err := ioutil.ReadFile(filepath)
	if err != nil {
		return nil, err
	}

	var c Config
	err = json.Unmarshal(raw, &c)
	if err != nil {
		return nil, err
	}

	defaultFileMode, err := strconv.ParseInt(c.DefaultJobPermString, 8, 32)
	if err != nil {
		return nil, err
	}

	c.DefaultJobPerm = os.FileMode(defaultFileMode)
	return &c, err
}