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

View File

@ -10,7 +10,10 @@ import "path/filepath"
import "golang.org/x/crypto/bcrypt" import "golang.org/x/crypto/bcrypt"
func printErr (format string, values ...any) { 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 { func serviceUser (service string) string {
@ -56,6 +59,22 @@ func main () {
os.Exit(1) 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 // define commands
hashCommand := flag.NewFlagSet("hash", flag.ExitOnError) hashCommand := flag.NewFlagSet("hash", flag.ExitOnError)
hashCost := hashCommand.Uint("cost", uint(bcrypt.DefaultCost), "Cost of the hash") hashCost := hashCommand.Uint("cost", uint(bcrypt.DefaultCost), "Cost of the hash")
@ -83,22 +102,39 @@ func main () {
ownRecursive := ownCommand.Bool ("r", false, ownRecursive := ownCommand.Bool ("r", false,
"Whether or not to recurse into sub-directories") "Whether or not to recurse into sub-directories")
flag.Parse()
// execute correct command // execute correct command
if len(os.Args) < 2 {
flag.Usage()
os.Exit(1)
}
subCommandArgs := os.Args[2:]
switch os.Args[1] { switch os.Args[1] {
case "hash": case "hash":
hashCommand.Parse(subCommandArgs)
execHash(int(*hashCost), *hashText) execHash(int(*hashCost), *hashText)
case "adduser": case "adduser":
addUserCommand.Parse(subCommandArgs)
execAdduser(*addUserService) execAdduser(*addUserService)
case "deluser": case "deluser":
delUserCommand.Parse(subCommandArgs)
execDeluser(*delUserService) execDeluser(*delUserService)
case "auth": case "auth":
authCommand.Parse(subCommandArgs)
execAuth(*authService, *authUser) execAuth(*authService, *authUser)
case "own": case "own":
ownCommand.Parse(subCommandArgs)
execOwn(*ownService, *ownFile, *ownRecursive) execOwn(*ownService, *ownFile, *ownRecursive)
} }
} }
func execHash (cost int, key string) { func execHash (cost int, key string) {
if key == "" {
printErr("please specify key text content")
os.Exit(1)
}
if cost < bcrypt.MinCost { if cost < bcrypt.MinCost {
printErr("cost is too low, must be at least %v", bcrypt.MinCost) printErr("cost is too low, must be at least %v", bcrypt.MinCost)
os.Exit(1) os.Exit(1)