#! /usr/bin/env perl use strict; use warnings; use 5.020; use Getopt::Long::Descriptive; use lib 'lib'; use My::Mailserver::Schema; my ( $opt, $usage ) = describe_options( "domain.pl %o", [ 'source|s=s', 'The source of the alias' ], [ 'target|t=s', 'The destination for the alias' ], [ 'domain|d=s', 'The domain to operate on' ], [ 'add|a', 'Add a new domain (requires domain)' ], [ 'remove|r', 'Remove a domain (requires domain)' ], [ 'list|l', 'List all domains' ], [ 'help', 'Print usage message and exit', { shortcircuit => 1 } ], ); say( $usage->text ), exit if $opt->help; my $schema = My::Mailserver::Schema->connect('MAILSERVER_MANAGER'); my $rs = $schema->resultset('VirtualAlias'); if ( $opt->list ) { my $line = "%5s | %20s | %20s | %20s\n"; printf $line, 'ID', 'Domain', 'Alias', 'Destination'; while ( my $result = $rs->next ) { printf $line, $result->id, $result->domain->name, $result->source, $result->destination; } } elsif ( $opt->domain && $opt->source && $opt->target ) { my $domain = $schema->resultset('VirtualDomain')->find({ name => $opt->domain }); my $alias = $domain->find_or_new_related('virtual_aliases', { source => $opt->source, destination => $opt->target }); if ( $opt->add && $domain ) { if ( $alias->in_storage ) { die "Alias already exists"; } else { $alias->insert; say "Created new alias"; } } elsif ( $opt->remove ) { if ( $alias->in_storage ) { $alias->delete; say "Deleted alias"; } else { die "Alias not found"; } } } else { die "Must provide domain, source, and target"; }