#! /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", [ 'email|e=s', 'The users new email' ], [ 'password|p=s', 'The password for the user' ], [ 'domain|d=s', 'The domain to operate on' ], [ 'add|a', 'Add a new user (requires domain, email and password)' ], [ 'remove|r', 'Remove a user (requires domain and email)' ], [ 'update|u', 'Update user (requires domain, email and password' ], [ 'list|l', 'List all users' ], [ '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('VirtualUser'); if ( $opt->list ) { my $line = "%5s | %20s | %20s\n"; printf $line, 'ID', 'Domain', 'Email'; while ( my $result = $rs->next ) { printf $line, $result->id, $result->domain->name, $result->email; } } elsif ( $opt->domain && $opt->email ) { my $domain = $schema->resultset('VirtualDomain')->find({ name => $opt->domain }); my $alias = $domain->find_or_new_related('virtual_users', { email => $opt->email, }); if ( $opt->add && $domain ) { if ( $alias->in_storage ) { die "Alias already exists"; } elsif( $opt->password ) { $alias->password( $opt->password ); $alias->insert; say "Created new user"; } else { die "Requires password"; } } elsif ( $opt->update && $domain ) { if ( $alias->in_storage ) { $alias->password( $opt->password ); $alias->update; say "Updated password"; } else { die "User not found"; } } elsif ( $opt->remove ) { if ( $alias->in_storage ) { $alias->delete; say "Deleted user"; } else { die "User not found"; } } } else { die "Must provide domain and email"; }