Fixed my god awful 3am code

This commit is contained in:
Sasha Koshka 2023-05-30 11:07:57 -04:00
parent 6f876b2a17
commit 92b93abb13
1 changed files with 37 additions and 1 deletions

View File

@ -10,7 +10,10 @@ import "path/filepath"
import "golang.org/x/crypto/bcrypt"
func printErr (format string, values ...any) {
fmt.Fprintf(os.Stderr, os.Args[0] + ": " + format, values...)
fmt.Fprintf (
flag.CommandLine.Output(),
os.Args[0] + ": " + format + "\n",
values...)
}
func serviceUser (service string) string {
@ -56,6 +59,22 @@ func main () {
os.Exit(1)
}
flag.Usage = func () {
out := flag.CommandLine.Output()
fmt.Fprintf(out, "Usage of %s:\n", os.Args[0])
fmt.Fprintf(out, " hash\n")
fmt.Fprintf(out, " Generate a bcrypt hash of a key\n")
fmt.Fprintf(out, " adduser\n")
fmt.Fprintf(out, " Add a system user to run a service as\n")
fmt.Fprintf(out, " deluser\n")
fmt.Fprintf(out, " Remove a user added with adduser\n")
fmt.Fprintf(out, " auth\n")
fmt.Fprintf(out, " Authorize a system user to access a service's files\n")
fmt.Fprintf(out, " own\n")
fmt.Fprintf(out, " Give ownership of a file to a service\n")
os.Exit(1)
}
// define commands
hashCommand := flag.NewFlagSet("hash", flag.ExitOnError)
hashCost := hashCommand.Uint("cost", uint(bcrypt.DefaultCost), "Cost of the hash")
@ -83,22 +102,39 @@ func main () {
ownRecursive := ownCommand.Bool ("r", false,
"Whether or not to recurse into sub-directories")
flag.Parse()
// execute correct command
if len(os.Args) < 2 {
flag.Usage()
os.Exit(1)
}
subCommandArgs := os.Args[2:]
switch os.Args[1] {
case "hash":
hashCommand.Parse(subCommandArgs)
execHash(int(*hashCost), *hashText)
case "adduser":
addUserCommand.Parse(subCommandArgs)
execAdduser(*addUserService)
case "deluser":
delUserCommand.Parse(subCommandArgs)
execDeluser(*delUserService)
case "auth":
authCommand.Parse(subCommandArgs)
execAuth(*authService, *authUser)
case "own":
ownCommand.Parse(subCommandArgs)
execOwn(*ownService, *ownFile, *ownRecursive)
}
}
func execHash (cost int, key string) {
if key == "" {
printErr("please specify key text content")
os.Exit(1)
}
if cost < bcrypt.MinCost {
printErr("cost is too low, must be at least %v", bcrypt.MinCost)
os.Exit(1)