#!/usr/bin/perl
# Copyright 2018 James Ziobro
#	Software provided under GNU GPL: https://www.gnu.org/licenses/gpl.txt
# VirtDomain.pl:	v2 1/2019
# read assorted aliases formated files and create virtuser and aliases files to handle like virtual domains
#	filename is used as "domain name"
#	"domain name" excludes any directory part of FILENAME
#	Use name directly if it already includes an '@' sign.

my $A = "aliases.CKP";
my $V = "virtusers.CKP";
my $FIRST = "azz-";    # something that wont clash with any real aliases or mailboxes

eval '$' . $1 . '$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;

# process any FOO=bar switches

open( ALIASES, ">" . $A )
  or die "\nError opening $A : $!";
open( VIRTUSER, ">" . $V )
  or die "\nError opening $V : $!";

my $aliasN = 0;
while (<>) {
    $aliasN++;
    $ARGV =~ s/.*\///;    # filename without path is the domain name
    chomp;                # strip record separator
    next if /\s*\#/;      # skip comments
    next if /^\s*$/;      # skip blanks
    print $ARGV . ':' . $_ . "\n";
    my ( $name, $alias ) = split /:/, $_, 2;
    $name =~ s/\s*//g;    # kill all whitespace!
    print ALIASES $FIRST, $aliasN, ":", $alias, "\n";

    # keep domain if already specified in name
    # otherwise add filename as domain
    my $virtual_name = ( $name =~ /@/ ) ? $name : $name . '@' . $ARGV;
    print VIRTUSER $virtual_name, "	", $FIRST, $aliasN, "\n";

}
