#!/usr/bin/perl
 
use warnings;
use strict;
use feature 'say';
use File::Slurp;
use Env 'HOME';
use MailIdentity qw(SaveID ReadID);
##use Locale::TextDomain ('tb-att', './locale/');
use Locale::TextDomain ('tb-att', '/usr/share/thunderbird-attachment/locale');
use POSIX;
setlocale( LC_MESSAGES, '' );


my @profile = read_file("$HOME/.thunderbird/profiles.ini");
my $PATH;
for (@profile)
{
	if ($_ =~ /Path=(.+)/)
	{
		$PATH = $1;
		last;
	}
}
die __":: Couldn't find a valid profile!\n" unless $PATH;
my @prefsjs = read_file("$HOME/.thunderbird/$PATH/prefs.js");
my $RID = ReadID;
my @IDS;
print "\n";
for (@prefsjs)
{
	if ($_ =~ /\"mail\.identity\.(id\d+)\.useremail\", \"(.+)\"/)
	{
		push @IDS, { id => $1, useremail => $2 };
	}
}
die __":: No valid email address found!\n" unless @IDS;

my $ids_size = scalar @IDS;
for ( my $i = 0; $i < $ids_size; $i++ )
{
	print '[', $i + 1, "] $IDS[$i]->{id} -> $IDS[$i]->{useremail}";
	($IDS[$i]->{id} eq $RID) ? print " (*)\n" : print "\n";
}
say __"\n:: please choose your default email address (type corresponding number)";
print __":: [ q = quit progam ]\n>";
my $choice;
    while (  $choice =  <STDIN> )
    {
            no warnings;
            chomp $choice;
            $choice =~ s/^\s+//;
            $choice =~ s/\s+$//;
	    do {say __":: quitting ..."; exit 1} if $choice eq 'q';
            last if $choice =~/^\d+$/ and $choice ~~ [ 1 .. $ids_size ];
            say __":: WRONG SELECTION!\n:: please choose your default email address (type corresponding number)";
	    print __":: [ q = quit progam ]\n>";
    }

SaveID("id${choice}");
$choice--;
say __x (":: {mail} ({id}) is now the default sender address!",
		mail => $IDS[$choice]->{useremail},
		id => $IDS[$choice]->{id});
say ":: Bye";
