author | Thor77
<thor77@thor77.org> 2019-10-18 22:19:39 UTC |
committer | Alberto Bertogli
<albertito@blitiri.com.ar> 2019-10-19 12:06:30 UTC |
parent | 9dea372d96d434ad2a080d18fabba64261b47dc1 |
cmd/chasquid-util/chasquid-util.go | +52 | -0 |
cmd/chasquid-util/test.sh | +9 | -0 |
diff --git a/cmd/chasquid-util/chasquid-util.go b/cmd/chasquid-util/chasquid-util.go index 345ee44..ced89ed 100644 --- a/cmd/chasquid-util/chasquid-util.go +++ b/cmd/chasquid-util/chasquid-util.go @@ -36,6 +36,7 @@ Usage: chasquid-util [options] aliases-resolve <address> chasquid-util [options] domaininfo-remove <domain> chasquid-util [options] print-config + chasquid-util [options] aliases-add <source> <target> Options: -C --configdir=<path> Configuration directory @@ -65,6 +66,7 @@ func main() { "aliases-resolve": aliasesResolve, "print-config": printConfig, "domaininfo-remove": domaininfoRemove, + "aliases-add": aliasesAdd, } for cmd, f := range commands { @@ -269,3 +271,53 @@ func domaininfoRemove() { Fatalf("Error removing file: %v", err) } } + +// chasquid-util aliases-add <source> <target> +func aliasesAdd() { + source := args["<source>"].(string) + target := args["<target>"].(string) + + user, domain := envelope.Split(source) + if domain == "" { + Fatalf("Domain required in source address") + } + + // Ensure the domain exists. + if _, err := os.Stat(filepath.Join(configDir, "domains", domain)); os.IsNotExist(err) { + Fatalf("Domain doesn't exist") + } + + conf, err := config.Load(configDir + "/chasquid.conf") + if err != nil { + Fatalf("Error reading config") + } + os.Chdir(configDir) + + // Setup alias resolver. + r := aliases.NewResolver() + r.SuffixSep = conf.SuffixSeparators + r.DropChars = conf.DropCharacters + + r.AddDomain(domain) + aliasesFilePath := filepath.Join("domains", domain, "aliases") + if err := r.AddAliasesFile(domain, aliasesFilePath); err != nil { + Fatalf("%s: error loading %q: %v", domain, aliasesFilePath, err) + } + + // Check for existing entry. + if _, ok := r.Exists(source); ok { + Fatalf("There's already an entry for %v", source) + } + + // Append the new entry. + aliasesFile, err := os.OpenFile(aliasesFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + Fatalf("Couldn't open %s: %v", aliasesFilePath, err) + } + _, err = fmt.Fprintf(aliasesFile, "%s: %s\n", user, target) + if err != nil { + Fatalf("Couldn't write to %s: %v", aliasesFilePath, err) + } + aliasesFile.Close() + fmt.Println("Added alias") +} diff --git a/cmd/chasquid-util/test.sh b/cmd/chasquid-util/test.sh index 88bb6fb..57d251c 100755 --- a/cmd/chasquid-util/test.sh +++ b/cmd/chasquid-util/test.sh @@ -80,4 +80,13 @@ if [ "$C" != "hostname: \"$HOSTNAME\"" ]; then exit 1 fi +if r aliases-add alias2@domain target > /dev/null; then + ALIAS=$(grep alias2 .config/domains/domain/aliases) + if [ "$ALIAS" != "alias2: target" ]; then + echo alias-add failed + echo output: "$ALIAS" + exit 1 + fi +fi + success