gocage/cmd/properties.go

126 lines
2.4 KiB
Go

package cmd
import (
"os"
"fmt"
"errors"
"reflect"
"strconv"
"strings"
)
func GetJailProperties(args []string) {
var props []string
var jail *Jail
var err error
if len(args) > 0 {
for i, a := range args {
// Last arg is the jail name
if i == len(args)-1 {
jail, err = getJailFromArray(a, []string{""}, gJails)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
os.Exit(1)
}
} else {
props = append(props, a)
}
}
}
if len(jail.Name) == 0 || len(args) == 0 {
// TODO : Show help
fmt.Printf("Error\n")
return
}
if isStringInArray(props, "all") {
var result []string
result = getStructFieldNames(*jail, result, "")
props = result
}
for _, p := range props {
v, err := getJailProperty(jail, p)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
return
} else {
fmt.Printf("%s = %s\n", p, v)
}
}
}
func getJailProperty(jail *Jail, propName string) (string, error) {
val, _, err := getStructFieldValue(jail, propName)
if err != nil {
return "", err
}
switch val.Kind() {
case reflect.String:
return val.String(), nil
case reflect.Int:
return strconv.FormatInt(val.Int(), 10), nil
case reflect.Bool:
return strconv.FormatBool(val.Bool()), nil
default:
return "", errors.New(fmt.Sprintf("Error: Unknown type for property %s: %s\n", propName, val.Kind()))
}
return "", errors.New("Unknown error in getJailProperty")
}
func SetJailProperties(args []string) {
type properties struct {
name string
value string
}
var jail Jail
var props []properties
if len(args) > 0 {
for i, a := range args {
// This is the jail name
if i == len(args)-1 {
jail.Name = a
} else {
kv := strings.Split(a, "=")
if len(kv) != 2 {
// TODO : Show help
fmt.Printf("Error parsing args: %s\n", a)
return
} else {
p := properties{name: kv[0], value: kv[1]}
props = append(props, p)
}
}
}
}
if len(jail.Name) == 0 || len(args) == 0 {
// TODO : Show help
fmt.Printf("Error\n")
return
}
cj, err := getJailFromArray(jail.Name, []string{""}, gJails)
if err != nil {
fmt.Printf("Error getting jail %s: %v\n", jail.Name, err)
return
}
for _, p := range props {
err := setStructFieldValue(cj, p.name, p.value)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
return
} else {
fmt.Printf("%s: %s set to %s\n", cj.Name, p.name, p.value)
}
}
cj.WriteConfigToDisk(false)
}