#!/usr/bin/perl
#
#     SuSEVbox 1.1
#       
#  Autor:     Michael Burghart <mb@suse.de>
#  Copyright: Michael Burghart, GPL
#
#  Provides an easy means of using your PC as an answer phone.
#  It may be setup by SuSEVboxConfig. Furthermore it needs the kernel
#  to be compiled using ISDN_AUDIO support
#
#
#
#########################################################################
#----------------- some preliminary stuff ------------------------------#
BEGIN { push(@INC,"/usr/lib/susevbox") };
use Tk;
use Tk::Dialog;
use Tk::BrowseEntry;
use File::Copy;
use Time::Local;
use POSIX;
use Fs;
use Shell qw(susevboxplay);
#----------------------------------------------------------------------#
#------------------ some useful default settings ----------------------#
#----------------------------------------------------------------------#
$defaultfont = "8x13bold";
$version = "SuSEVbox 1.1";
$helppath = "/usr/lib/susevbox/xvbox.hlp";
$confpath = "/tmp/vboxstartscript";
$messagepath = "/usr/lib/susevbox/messages";
$selected = "Select all entries";
$old_selected = "Select all entries";
$laenge = 0;
$laenge_max = 72;
$stop = 2;
$getmessage = 1;
$recording = 0;
$vboxsearch = "";
$old_vboxsearch = "";
%liste = {};
$delete = "";
$stoploop = 1;
#----------------------------------------------------------------------#
#--------------------- do it! -----------------------------------------#
#----------------------------------------------------------------------#
&readrcfile;
&main;
#----------------------------------------------------------------------#
#-------------------- main --------------------------------------------#
#----------------------------------------------------------------------#
sub main {
    $top        = MainWindow->new();
    $top->wm("title",$version);
    $frame1 = $top->Frame(-bd => '2', -relief => groove)
	->pack(-side => 'top',
	       -expand => 'yes',
	       -fill => 'both',
	       -pady => 7,
	       -padx => 7);
    $frame2 = $top->Frame(-bd => '2', -relief => groove)
	->pack(-side => 'top',
	       -expand => 'yes',
	       -fill => 'both',
	       -pady => 7,
	       -padx => 7);
    $frame3 = $top->Frame(-bd => '2', -relief => groove)
	->pack(-side => 'top',
	       -expand => 'yes',
	       -fill => 'both',
	       -pady => 7,
	       -padx => 7);
    $listbox = $frame1->ScrlListbox(-width => '70', -height => '8',
				     -bg => 'white',
				    -selectmode => 'single',
				    -font => $defaultfont,
				    -exportselection => 0)
	->pack(-side => 'top');
    $listbox->configure(-fg => 'blue');
    $play_button = $frame2->Button(-text => 'Play',
				   -font => $defaultfont,
				   -command => \&playentry,
				   -width => '5')
	->pack(-side => 'left', -padx => 3);
    $abort_button = $frame2->Button(-text => 'Stop',
				   -font => $defaultfont,
				   -command => \&stopentry,
				   -width => '5')
	->pack(-side => 'left', -padx => 3);

    $delete_button = $frame2->Button(-text => 'Del.',
				     -font => $defaultfont,
				     -fg => 'red',
				     -activeforeground => 'red',
				     -command => \&delentry,
				     -width => '5')
	->pack(-side => 'left', -padx => 3);
    $rec_button = $frame2->Button(-text => 'Rec.',
				  -font => $defaultfont,
				  -fg => 'blue',
				  -activeforeground => 'blue',
				  -width => '5',
				  -command => sub { $stop = 1 ; &record_messages ; &meter})
	->pack(-side => 'left', -padx => 3);
    $vboxconf_button = $frame2->Button(-text => 'Conf.',
				       -font => $defaultfont,
				       -fg => 'blue',
				       -width => '5',
				       -activeforeground => 'blue',
				       -command => \&vboxconf)
	->pack(-side => 'left', -padx => 3);
    $select_button = $frame2->BrowseEntry(-label => 'Select entries',
					  -textvariable => \$selected,
					  -state => 'readonly')
	->pack(-side => 'left', -padx => 3);
    $select_button->insert("end","Select all entries");
    $select_button->insert("end","Select unread entries");
    $select_button->insert("end","Unknown");
    $volume_scale = $frame1->Scale(-orient => 'horizontal',
				   -length => '20',
				   -from => '0',
				   -to => '70',
				   -tickinterval => '5',
				   -variable => \$volume)
	->pack(-side => 'left', -fill => 'x',
	       -expand => 'yes');
    $ok_button = $frame3->Button(-text => 'Quit',
				 -font => $defaultfont,
				 -command => \&exitvbox,
				 -width => '5')
	->pack(-side => 'left', -padx => 3);
    $save_button = $frame3->Button(-text => 'Reload',
				   -font => $defaultfont,
				   -command => \&readrcfile,
				   -width => '5')
	->pack(-side => 'left', -padx => 3);
    $help_button = $frame3->Button(-text => 'Help',
				   -font => $defaultfont,
				   -command => \&help,
				   -width => '5')
	->pack(-side => 'left', -padx => 3);
    $config_button = $frame3->Button(-text => 'About',
				     -font => $defaultfont,
				     -command => \&about,
				     -width => '5')
	->pack(-side => 'left', -padx => 3);
    $listbox->delete("0","end");
    open(VBOXCONF,"$vboxconfpath/vbox.conf");
    while ($line = <VBOXCONF>) {
	if ($line =~ /^\d{3,10}/) {
	    ($number,$name,$real1,$real2) = split(" ",$line);
	    if ($name ne "STANDARD-OWNER") {
		$select_button->insert("end","$real1 $real2");
	    }
	}
    }
    close(VBOXCONF);
    $listbox->bind("<Double-Button-1>",\&playentry);
    $listbox->bind("<Double-Button-3>",\&stopentry);
    &get_directory;
    &actualize_directory;
    MainLoop();
}
#----------------------------------------------------------------------#
#--------------------- play the selected entry ------------------------#
#----------------------------------------------------------------------#
sub playentry {
    $nummer = $listbox->curselection();
    $bla = $listbox->get("$nummer");
    $audiofile = $array_file{$bla};
    system("$playscript $audiofile $volume 2>/dev/null&");
    ($number,$destname,$dummy1,$dummy2) = split ('\n',$line);
    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,
     $mtime,$ctime,$blksize,$blocks) = stat($audiofile);
    if ($mode eq "33152") { 
	chop($bla);
	chop($bla);
	chop($bla);
	$file_array{"$audiofile"} = $bla;
	%array_file = reverse(%file_array);
	$listbox->delete("$nummer");
	$listbox->insert("$nummer","$bla");    
    }
    chmod(0744,$audiofile);
    $listbox->selectionSet($nummer);
}
#----------------------------------------------------------------------#
#----------------------- delete the selected entry --------------------#
#----------------------------------------------------------------------#
sub delentry {
    $nummer = $listbox->curselection();
    $bla = $listbox->get("$nummer");
    $blubb = $array_file{"$bla"};
    delete $file_array{"$blubb"};
    delete $array_file{"$bla"};
    unlink("$blubb");
    @files = <$incoming/*>;
    $listbox->delete("0","end");
    &get_directory;
    $listbox->selectionSet("$nummer");
    $listbox->see("$nummer");
}
#----------------------------------------------------------------------#
#---------------------- select entries not in use ---------------------#
#----------------------------------------------------------------------#
sub select_entries {
    unless (Exists $entry_selection) {
	$maingeometry = $top->wm("geometry");
	$maingeometry =~ /^(\d{1,3})x(\d{1,3})\+(\d{1,3})\+(\d{1,3})$/;
	$xpos = $3 + 160;
	$ypos = $4 + 120;
	$entry_selection        = $top->Toplevel();
	$entry_selection->wm("title","Select range of messages");
	$entry_selection->wm("geometry","+$xpos+$ypos" );
	$select_frame = $entry_selection->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
    } else {
	$entry_selection->raise();
	$entry_selection->focus();
    }
}
#----------------------------------------------------------------------#
#----------------------- get incoming directory -----------------------#
#----------------------------------------------------------------------#
sub get_directory {
    foreach (@files) {
	$filename = $_;
	$line = `vboxmode $_`;
	($e,$create,$comp,$length,$name1,$number1,$d1,$d2) = split('\n',$line);
	$name1 =~ /.+:(.+)/;
	$destname = $1;
	$number1 =~ /.+:(.+)/;
	$number = $1;
	$create =~ /.+:\s.{3}\s(.+:\d{2})/;
	$zeit = $1;
	($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,
	 $mtime,$ctime,$blksize,$blocks) = stat;
	$groesse = $size/3800;
	$Groesse = minsec(int($groesse));
	$Zeit = substr($zeit,0,20);
	$destname = fillup($destname,20);
	$number   = fillup($number,20);
	if ($mode eq "33152") { 
	    if ($destname=~   /$selected/) {
		&insertbox("0","$destname $number $Zeit $Groesse  NEW",$filename);
	    } elsif ($selected eq "Select unread entries") {
		&insertbox("0","$destname $number $Zeit $Groesse  NEW",$filename);
	    } elsif ($selected eq "Select all entries") {
		&insertbox("0","$destname $number $Zeit $Groesse  NEW",$filename);
	    }
	} else {
	    if ($destname =~  /$selected/) {
		&insertbox("0","$destname $number $Zeit $Groesse",$filename);
	    } elsif ($selected eq "Select all entries") {
		&insertbox("0","$destname $number $Zeit $Groesse",$filename);
	    }
	}
    }	
    $listbox->see("0");
    $listbox->selectionSet("0");
}
#------------------------------------------------------------------------#
#-------------------------- actualize incoming directory ----------------#
#------------------------------------------------------------------------#
sub actualize_directory  {
    if ($selected ne $old_selected) {
 	$listbox->configure(-bg => 'darkgrey');
	$listbox->update();
	$old_selected = $selected;
	$listbox->delete("0","end");
	&get_directory;
 	$listbox->configure(-bg => 'white');
    }
    @files = <$incoming/*>;
    $incominglength = $files;
    %array_file = reverse(%file_array);
    foreach (@files) {
	unless (exists($file_array{$_})) {
	    $line = `vboxmode $_ 2>&1`;
	    if ($line =~ /sample/) {
		last;
	    }
	    ($e,$create,$comp,$length,$name1,$number1,$d1,$d2) = split('\n',$line);
	    $name1 =~ /.+:(.+)/;
	    $destname = $1;
	    $number1 =~ /.+:(.+)/;
	    $number = $1;
	    $length =~ /.+:\s(\d{1,3})/;
	    $groesse = $1;
	    $create =~ /.+:\s.{3}\s(.+:\d{2})/;
	    $zeit = $1;
	    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,
	     $mtime,$ctime,$blksize,$blocks) = stat;
	    $groesse = $size/3800;
	    $Groesse = minsec(int($groesse));
	    $Zeit = substr($zeit,0,20);
	    $destname = fillup($destname,20);
	    $number   = fillup($number,20);
	    if ($mode eq "33152") { 
		&insertbox("0","$destname $number $Zeit $Groesse  NEW",$_);
	    } else {
		&insertbox("0","$destname $number $Zeit $Groesse",$_);
	    }
	}
    }
    $top->after(100,\&actualize_directory);
}
#------------------------------------------------------------------------#
#----------------------- fillup entries for listbox ---------------------#
#------------------------------------------------------------------------#
sub fillup {
    my $input = shift;
    my $Laenge = shift;
    my $laenge = length($input);
    while ($laenge <= $Laenge) {
	$input =  $input . " ";
	$laenge++;
	if ($laenge == $Laenge) {
	    return "$input";
	}
    }
}
#-----------------------------------------------------------------------#
#------------------------ convert seconds to 00:00 ---------------------#
#-----------------------------------------------------------------------#
sub minsec {
    $time = shift;
    if ($time >= 60) {
	$minuten  = int(($time / 60));
	$sekunden = $time - ($minuten * 60);
	if ($minuten <= 9) {
	    $minuten = "0$minuten";
	}
	if ($sekunden <= 9) {
	    $sekunden = "0$sekunden";
	}
    } elsif ($time < 60) {
	$minuten = "00";
	$sekunden = $time;
	if ($sekunden <= 9) {
	    $sekunden = "0$sekunden";
	}
    } else {
	$minuten  = "00";
	$sekunden = "00";
    }
    return "$minuten:$sekunden";
}
#-----------------------------------------------------------------------#
#------------------ insert entry into listbox --------------------------#
#-----------------------------------------------------------------------#
sub insertbox {
    ($position,$string,$file) = @_;
    $listbox->insert($position,$string);
    $file_array{"$file"} = $string;
}
#-----------------------------------------------------------------------#
#------------------ stop playing message -------------------------------#
#-----------------------------------------------------------------------#
sub stopentry {
    system("killall pvftoau 2>/dev/null");
}
#-----------------------------------------------------------------------#
#------------------ read config file -----------------------------------#
#-----------------------------------------------------------------------#
sub readrcfile {
    open(RCFILE,"$ENV{HOME}/.susevboxrc");
    while ($line = <RCFILE>) {
	if ($line =~ /#\s*Volume/) {
	    $line = <RCFILE>;
	    chop($volume = $line);
	}
	if ($line =~ /#\s+Vboxconfpath/) {
	    $line = <RCFILE>;
	    chop($vboxconfpath = $line);
	}
	if ($line =~ /#\s+Playscript/) {
	    $line = <RCFILE>;
	    chop($playscript = $line);
	}
	if ($line =~ /#\s+Incoming Files/) {
	    $line = <RCFILE>;
	    chop($incoming = $line);
	    @files = <$incoming/*>;
	}
	if ($line =~ /#\s+Messages/) {
	    $line = <RCFILE>;
	    chop($messagepath = $line);
	}
    }
    if (Exists $listbox) {
	$listbox->delete("0","end");
	$select_button->delete("0","end");
	$select_button->insert("end","Select all entries");
	$select_button->insert("end","Select unread entries");
        $select_button->insert("end","Unknown");
	open(VBOXCONF,"$vboxconfpath/vbox.conf");
	while ($line = <VBOXCONF>) {
	    if ($line =~ /^\d{3,10}/) {
		($number,$name,$real1,$real2) = split(" ",$line);
		$select_button->insert("end","$real1 $real2");
	    }
	}
	close(VBOXCONF);
	&get_directory;
    }
}
#-----------------------------------------------------------------------#
#------------------------ help -----------------------------------------#
#-----------------------------------------------------------------------#
sub help {
    unless (Exists $hilfe) {
	$maingeometry = $top->wm("geometry");
	$maingeometry =~ /^(\d{1,3})x(\d{1,3})\+(\d{1,3})\+(\d{1,3})$/;
	$xpos = $3 + 160;
	$ypos = $4 + 120;
	$hilfe        = $top->Toplevel();
	$hilfe->wm("title","Help on $version");
	$hilfe->wm("geometry","+$xpos+$ypos" );
	$helpframe1 = $hilfe->Frame(-bd => '2', 
				    -relief => 'flat')
	    ->pack(-side => 'top', -expand => 'yes', -fill => 'both');
	$helpframe2 = $hilfe->Frame(-bd => '2', 
				    -relief => 'flat')
	    ->pack(-side => 'top', -expand => 'yes', -fill => 'both');
	$helptext = $helpframe1->Text(-wrap => 'none',
				      -state => 'normal',
				      -bg => 'white',
				      -fg => 'black')
	    ->pack(-side => 'left');
	$yscroll  = $helpframe1->Scrollbar(-command => [yview => $helptext])
	    ->pack(-side => 'left', - fill => 'y');
	$helptext->configure(-yscrollcommand => [set => $yscroll]);
	$okbutton = $helpframe2->Button(-text => 'OK', 
					-command => sub {$hilfe->destroy()},
					-font => $defaultfont, -width => '15')
	    ->pack(-side => 'bottom', -pady => '2m', -padx => '2m');
	open(HELP,$helppath);
	while ($line = <HELP>) {
	    $helptext->insert("end",$line);
	}
	$helptext->configure(-state => 'disabled');
	close(HELP);
	

    } else {
	$hilfe->raise();
	$hilfe->focus();
    }
}
#-----------------------------------------------------------------------#
#---------------------------- about this tool --------------------------#
#-----------------------------------------------------------------------#
sub about {
    unless (Exists $about) {
	$maingeometry = $top->wm("geometry");
	$maingeometry =~ /^(\d{1,3})x(\d{1,3})\+(\d{1,3})\+(\d{1,3})$/;
	$xpos = $3 + 160;
	$ypos = $4 + 120;
	$about        = $top->Toplevel();
	$about->wm("title","About $version");
	$about->wm("geometry","+$xpos+$ypos" );
	$label1 = $about->Label(-text => "$version", 
				-font => $defaultfont)
	    ->pack(-side => 'top');
	$label2 = $about->Label(-text => 'was written by:', 
				-font => $defaultfont)
	    ->pack(-side => 'top');
	$label3 = $about->Label(-text => 'Michael Burghart <mb@suse.de>',
				-font => $defaultfont)
	    ->pack(-side => 'top');
	$okbutton    = $about->Button(-text => "OK", 
				      -command => sub {$about->destroy()},
				      -font => $defaultfont, -width => '15')
	    ->pack(-side => 'bottom', -pady => '2m', -padx => '2m');
    } else {
	$about->raise();
	$about->focus();
    }
}
#-----------------------------------------------------------------------#
#--------------------- records messages --------------------------------#
#-----------------------------------------------------------------------#y
sub record_messages {
    unless (Exists $record) {
	$maingeometry = $top->wm("geometry");
	$maingeometry =~ /^(\d{1,3})x(\d{1,3})\+(\d{1,3})\+(\d{1,3})$/;
	$xpos = $3 + 160;
	$ypos = $4 + 120;
	$record        = $top->Toplevel();
	$record->wm("title","Record messages \"$messagepath\"");
	$record->wm("geometry","+$xpos+$ypos" );
	$frame2 = $record->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$frame3 = $record->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$frame4 = $record->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$frame5 = $record->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$messagelabel = $frame2->Label(-text => "Select message:",
				  -font => $defaultfont)
	    ->pack(-side => left,
		   -pady => '0.8',
		   -padx => 0);
	$browse_messages = $frame2->BrowseEntry(-label => 'Browse messages',
						-textvariable => \$browseentry,
						-state => 'readonly',
						-width => '30')
	    ->pack(-side => left,
		   -pady => '0.8',
		   -padx => 0);
	foreach (<$messagepath/*>) {
	    /.+\/([a-zA-Z]*\.msg$)/;
           $browse_messages->insert("end",$1);
	}
	$browse_messages->insert("end","RECORD PRIVATE MESSAGE");
	$browseentry = "standard.msg";
	$priv_button = $frame2->Button(-text => 'Select file', 
				       -width => 15,
				       -font => $defaultfont,
				       -state => 'disabled',
				       -command => \&file_select)
	    ->pack(-side => left, -fill => both);
	$rectitel = $frame3->Label(-text => "Duration of recording", 
				   -fg => 'blue',
				   -font => $defaultfont,
				   -anchor => 'w')
	    ->pack(-side => 'top', -anchor => 'w');


	$reclength = $frame3->Label(-text => $laenge, -bg => 'blue',
				    -fg => 'white',
				    -font => $defaultfont,
				    -width => $laenge,
				    -anchor => 'e')
	    ->pack(-side => 'left');
	$rec_button = $frame4->Button(-text => 'Record', 
				     -width => 8,
				     -font => $defaultfont,
				      -fg => 'blue',
				      -activeforeground => 'blue',
				      -command => \&record)
	    ->pack(-side => left, -fill => both,
		   -padx => '3');
	$stop_button = $frame4->Button(-text => 'Stop rec.', 
				       -width => 8,
				       -font => $defaultfont,
				       -command => \&stop,
				       -state => 'disabled'
				       )
	    ->pack(-side => left, -fill => both,
		   -padx => '3');
	$save_button = $frame4->Button(-text => 'Stop play.', 
				     -width => 8,
				     -font => $defaultfont,
				       -command => \&stopentry)
	    ->pack(-side => right, -fill => both,
		   -padx => '3');
	$play_button = $frame4->Button(-text => 'Play', 
				     -width => 8,
				     -font => $defaultfont,
				       -command => \&play_test)
	    ->pack(-side => right, -fill => both,
		   -padx => '3');
	$del_button = $frame4->Button(-text => 'Delete', 
				     -width => 8,
				     -font => $defaultfont,
				      -fg => 'red',
				      -activeforeground => 'red',
				       -command => \&delete_msgs)
	    ->pack(-side => right, -fill => both,
		   -padx => '3');
	$esc_button = $frame5->Button(-text => 'Done', 
				      -width => 8,
				      -font => $defaultfont,
				      -command  => sub {$stop = 2; 
							$laenge = 0;  
							$record->destroy()})
	    ->pack(-side => left, -fill => both);
    }
}
#-----------------------------------------------------------------------#
#--------------------- fill up the meter--------------------------------#
#-----------------------------------------------------------------------#
sub meter {

    if ($browseentry ne "RECORD PRIVATE MESSAGE") {
	$record->wm("title","Record messages \"$messagepath/$browseentry\"");
    }
    if ($browseentry eq "RECORD PRIVATE MESSAGE") {
	$rec_button->configure(-state => 'disabled');
	$priv_button->configure(-state => 'normal');
    } elsif ($recording ne "1" && $browseentry ne "RECORD PRIVATE MESSAGE")  {
	$priv_button->configure(-state => 'disabled');
	$rec_button->configure(-state => 'normal');
    }
    if ($stop eq "0" && $laenge <= $laenge_max) {
	$reclength->configure(-width => $laenge, -text => $laenge);
	$laenge++;
    } elsif ($stop eq "0" && $laenge == $max_laenge) {
	$stop = 1;
	$reclength->configure(-width => $laenge, -text => $laenge);
    } elsif ($stop eq "1" && $laenge == $max_laenge) {
	$stop = 2;
	$reclength->configure(-width => $laenge, -text => $laenge);
    }
    $record->after(1000,\&meter);
}
#-----------------------------------------------------------------------#
#-------------------------- invoke a fileselector ----------------------#
#-----------------------------------------------------------------------#
sub file_select {
    $browse_messages->configure(-state => 'disabled');
    $rec_button->configure(-state => 'disabled');
    $play_button->configure(-state => 'disabled');
    $save_button->configure(-state => 'disabled');
    $stop_button->configure(-state => 'disabled');
    $esc_button->configure(-state => 'disabled');
    $selector = Fs->new($record, \&fsCallback,"Select a file");
    $selector->start("$messagepath");
}
#-----------------------------------------------------------------------#
#-------------------------- callback for fileselector ------------------#
#-----------------------------------------------------------------------#
sub fsCallback {
    my $file = shift;
    $record->wm("title","Record messages \"$messagepath/$file\"");
    $old_browseentry = $browseentry;
    $browse_messages->configure(-state => 'readonly');
    $rec_button->configure(-state => 'normal');
    $play_button->configure(-state => 'normal');
    $save_button->configure(-state => 'normal');
    $stop_button->configure(-state => 'normal');
    $esc_button->configure(-state => 'normal');
    $file =~ /.+\/([a-zA-Z.]+$)/;
    $fullpath = $1;	
    if ($fullpath ne "") {		   
	unless ($fullpath =~ /.*\.msg$/) {
	    $fullpath = $fullpath . ".msg";
	}		   
    } else {
	$fullpath = $old_browseentry;
    }
    @blubb = $browse_messages->get("0","end");
    $replace = 1;
    foreach (@blubb) {
	if (/$fullpath/) {
	    $replace = 0;
	}
    }
    if ($replace == 1) {		   
	$browse_messages->insert("0",$fullpath) ;
    }
    $browseentry = $fullpath;
}
#-----------------------------------------------------------------------#
#-------------------------- save the messages --------------------------#
#-----------------------------------------------------------------------#
sub save_msgs {
    @blubb = $browse_messages->get("0","end");
    foreach (@blubb) {
	if ($_ ne "RECORD PRIVATE MESSAGE") {
	    print "\nSaving file $vboxconfpath/messages/$_\n";
	}
    }
}
#-----------------------------------------------------------------------#
#-------------------------- nimmt das selektierte file auf -------------#
#-----------------------------------------------------------------------#
sub record {
    $result_button = "Yes";
    if (-e "$messagepath/$browseentry") {
	&errwin("File \"$browseentry\" already exist, overwrite?","question","YesNo","Overwrite \"$browseentry\"?");
    }
    if ($result_button eq "Yes") {
	$stop = 0;
	$laenge = 0;
	$recording = 1;
	$browse_messages->configure(-state => 'disabled');
	$play_button->configure(-state => 'disabled');
	$rec_button->configure(-state => 'disabled');
	$save_button->configure(-state => 'disabled');
	$del_button->configure(-state => 'disabled');
	$stop_button->configure(-state => 'normal');
	$esc_button->configure(-state => 'disabled');
	$browseentry =~ /(.+)\.msg$/;
	$file1 = $1;
	$tmpfile = `mktemp /var/tmp/susevbox.XXXXXX`;
	unless ($pid = fork) {
	    exec("wavrec -t72 -s8000 $tmpfile");
	}
    }
}
#-----------------------------------------------------------------------#
#-------------------------- nimmt das selektierte file auf -------------#
#-----------------------------------------------------------------------#
sub stop {
    $stop = 1;
    $recording = 0;
    $browse_messages->configure(-state => 'readonly');
    $play_button->configure(-state => 'normal');
    $rec_button->configure(-state => 'normal');
    $save_button->configure(-state => 'normal');
    $del_button->configure(-state => 'normal');
    $stop_button->configure(-state => 'disabled');
    $esc_button->configure(-state => 'normal');
    $dauer = $laenge-1;
    kill("9","$pid");
    $file2 = "$messagepath/$browseentry";
    unless (fork) {
	exec("susevboxconv \"$tmpfile\" \"$file2\" \"$volume\"");
    }
    wait;
    unlink(<"$tmpfile">);
}
#-----------------------------------------------------------------------#
#-------------------------- play recorded message ----------------------#
#-----------------------------------------------------------------------#
sub play_test {
    system("$playscript $messagepath\/$browseentry $volume 2>/dev/null&");
}
#-----------------------------------------------------------------------#
#-------------------- multi message window -----------------------------#
#-----------------------------------------------------------------------#
sub errwin {
    ($text,$icon,$type,$title) = @_;
    $result_button = $top->messageBox(-icon =>$icon, -type => $type,
				  -message => $text,
				  -title => $title);
}
#-----------------------------------------------------------------------#
#-------------------------- well, exit ---------------------------------#
#-----------------------------------------------------------------------#
sub delete_msgs {
    @necessary = ("standard.msg","beep.msg","panic.msg","timeout.msg","parkline.msg");
    $delete = "Yes";
    foreach (@necessary) {
	if (/$browseentry/) {
	    &errwin("File \"$browseentry\"is needed for vbox, delete?","question","YesNo","Delete \"$browseentry\"?");

	    if ($result_button eq "No") {
		$delete = "No";
	    }
	}
    }
    if ($delete eq "Yes") {
	if ($browseentry ne "RECORD PRIVATE MESSAGE") {
	    $browse_messages->delete("0","end");
	    unlink(<$messagepath/$browseentry>);
	    foreach (<$messagepath/*>) {
		/.+\/([a-zA-Z]*\.msg$)/;
		      $browse_messages->insert("end",$1);
		  }
		$browse_messages->insert("end","RECORD PRIVATE MESSAGE");
		$browseentry = "standard.msg";
	}
    }

}
#-----------------------------------------------------------------------#
#-------------------------- configure personal vbox.conf ---------------#
#-----------------------------------------------------------------------#
sub vboxconf {
    unless (Exists $vboxconf) {
	$maingeometry = $top->wm("geometry");
	$maingeometry =~ /^(\d{1,3})x(\d{1,3})\+(\d{1,3})\+(\d{1,3})$/;
	$xpos = $3 + 160;
	$ypos = $4 + 120;
	$vboxconf        = MainWindow->new();
	$vboxconf->wm("title","Configuration of \"$vboxconfpath/vbox.conf\"");
	$vboxconf->wm("geometry","+$xpos+$ypos" );
	$framet0 = $vboxconf->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$framet1 = $vboxconf->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$framet2 = $vboxconf->Frame(-bd => '2')
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$framet3 = $vboxconf->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$framet4 = $vboxconf->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$framet5 = $vboxconf->Frame(-bd => '2')
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$vboxsecs_label = $framet0->Label(-text => 'Sections found in vbox.conf',
					  -fg => 'blue')
	    ->pack(-side => 'top');;
	$vboxsecs = $framet1->ScrlListbox(-width => '70', -height => '4',
					  -font => $defaultfont, -bg => 'white',
					  -selectmode => 'single',
					  -exportselection => 0)
	    ->pack(-side => 'top');
	$add_sec = $framet2->Button(-text => 'Add section',
				    -width => '13',
				    -command => sub {},
				    -font => $defaultfont,
				    -command => \&action_add)
	    ->pack(-side => left, -padx => '3');

	$ed_sec = $framet2->Button(-text => 'Edit section',
				    -width => '13',
				    -command => sub {},
				    -font => $defaultfont,
				    -command => \&action_edit)
	    ->pack(-side => left, -padx => '3');
	$del_sec = $framet2->Button(-text => 'Delete section',
				    -width => '13',
				    -command => sub {},
				    -font => $defaultfont,
				    -fg => 'red',
				    -activeforeground => 'red',
				    -command => \&action_del)
	    ->pack(-side => left, -padx => '3');



	$vboxlists_label = $framet3->Label(-text => 'Calling entries found:',
					   -fg => 'blue')
	    ->pack(-side => 'top');

	$vboxlists = $framet3->Text(-width => '70', -height => '4',
				     -font => $defaultfont, -bg => 'white')
	    ->pack(-side => 'right');
	$yscroll  = $framet3->Scrollbar(-command => [yview => $vboxlists])
	    ->pack(-side => 'left', - fill => 'y');
	$vboxlists->configure(-yscrollcommand => [set => $yscroll]);
	$esc1button = $framet5->Button(-text => 'Done',
				       -width => '8', 
				       -command => sub {undef %liste ; undef %msgs ; undef %msns ; undef @names ; $vboxsearch = "" ; $old_vboxsearch = "" ;$vboxconf->destroy()},
				       -font => $defaultfont)
	    ->pack(-side => left, -padx => '3');
	$ok1button  = $framet5->Button(-text => 'Reload',
				       -width => '8',
				       -font => $defaultfont,
				       -command => sub  {$stoploop = "0"})
	    ->pack(-side => left, -padx => '3');
	$save1button  = $framet5->Button(-text => 'Save',
				       -width => '8',
				       -font => $defaultfont,
					 -command => \&vboxconfsave)
	    ->pack(-side => left, -padx => '3');
    } else {
	$vboxconf->raise();
	$vboxconf->focus();
    }
    $vboxsecs->bind("<Double-Button-1>",\&action_edit);
    $vboxlists->bind("<Double-Button-3>",\&insert_default);
    &findentries;
}
#-----------------------------------------------------------------------#
#-------------------------- inserts default entries --------------------#
#-----------------------------------------------------------------------#
sub insert_default {
    $vboxlists->insert("end","*    *    standard.msg    60    RINGS=4");
}
#-----------------------------------------------------------------------#
#-------------------------- find entries -------------------------------#
#-----------------------------------------------------------------------#
sub findentries {
    open(VBOXCONF,"$vboxconfpath/vbox.conf");
    select(VBOXCONF); $| = 1;
    select STDOUT;
    $vboxsecs->delete("0","end");
    while (<VBOXCONF>) {
	if (/^(\d{3,20})\s+([A-Za-z-]{1,20})\s+([a-zA-Zs]+)\s+([a-zA-Zs]{0,20})/) {
	    $msn = $1;
	    $id = $2;
	    push(@names,$id);
	    $name1 = $3;
	    $name2 = $4;
	    $id1 = fillup($id,20);
	    $msn = fillup($msn,20);
	    $Name = fillup("$name1 $name2",20);
	    $msns{"$id"} = "$msn    $id1   $Name";
	    $vboxsecs->insert("0","$id1  $msn  $Name ");
	}
    }
    close(VBOXCONF);
    foreach $item (@names) {



	open(VBOXCONF,"$vboxconfpath/vbox.conf");
	select(VBOXCONF); $| = 1;
	select STDOUT;
	while ($line = <VBOXCONF>) {
	    if ($line =~ /\[$item\]/) {

		$line = <VBOXCONF>;
                while ($line =~ /^[^\[]/ && $line =~ /^[^#]/) {

                      if ($line ne " ") {

			  $msgs{"$line"} = $item;
		      }
                      $line = <VBOXCONF>;
	        }
	    }
        }
        close(VBOXCONF);
    }
    foreach $item (@names) {	
	while (($first,$last) = each(%msgs)) {

	    if ($last eq $item) {
		if ($first ne " ") {
		    $liste{"$item"} = $liste{"$item"} . $first;
		}
	    }
	}
    }
    while (($first,$last) = each(%msgs)) {
	if ($last eq $item) {
	    $vboxlists->insert("end","$first");
	}
    }
    $vboxsecs->selectionSet("0");
    $vboxsecs->see("0");
    &findvboxlists; 	
}
#-----------------------------------------------------------------------#
#-------------------------- find entries -------------------------------#
#-----------------------------------------------------------------------#
sub findvboxlists {
    $bla = $vboxsecs->curselection();
    $blubb = $vboxsecs->get("$bla");
    $blubb =~ /^([A-Z-]+)/;
    $vboxsearch=  $1;
    $vboxlists_label->configure(-text => "Calling entries found for \"$vboxsearch\":");
    $blubber = $vboxlists->get("0.0","end");
    if ($vboxlists->get("0.0","end") ne $liste{"$vboxsearch"}) {
	$liste{"$old_vboxsearch"} = $vboxlists->get("0.0","end");
    }
    if ($old_vboxsearch ne $vboxsearch) {
	$old_vboxsearch = $vboxsearch;
	$vboxlists->delete("0.0","end");
	$vboxlists->insert("end","$liste{\"$vboxsearch\"}");
    }
    if ($stoploop eq "1") {
	$vboxconf->after(100,\&findvboxlists);
    } else {
	$stoploop = "1";
	%liste = {};
	%msns = {};
	%msgs = {};
	@names = ();
	$vboxsecs->delete("0","end");
	&findentries;
    }
}
#-----------------------------------------------------------------------#
#-------------------------- save vbox.conf -----------------------------#
#-----------------------------------------------------------------------#
sub vboxconfsave {
    if (-e "$vboxconfpath/vbox.conf") {
	&errwin("File \"$vboxconfpath/vbox.conf\" already exist, overwrite?","question","YesNo","Overwrite \"$vboxconfpath/vbox.conf\"?");
    }
    if ($result_button eq "Yes") {
	if (-e "$vboxconfpath/vbox.conf.bak") {
	    &errwin("File \"$vboxconfpath/vbox.conf.bak\" already exist, overwrite?","question","YesNo","Overwrite \"$vboxconfpath/vbox.conf\"?");
	}
	if ($result_button eq "Yes") {
	    copy("$vboxconfpath/vbox.conf","$vboxconfpath/vbox.conf.bak");	
	}
	open(TESTFILE,">$vboxconfpath/vbox.conf");
	select(TESTFILE); $| = 1;
	select STDOUT;
	

	print TESTFILE "#\n";
	print TESTFILE "#\n";
	print TESTFILE "# This vbox.conf file was automatically generated by\n";
	print TESTFILE "#              SuSEVbox\n";
	print TESTFILE "#\n";
	print TESTFILE "# For syntax of this file see vbox manual.\n";
	print TESTFILE "#\n";
	print TESTFILE "#\n";
	print TESTFILE "# CALLERIDS\n";
	print TESTFILE "#\n";
	print TESTFILE "# Format: PATTERN SECTION REALNAME\n";
	print TESTFILE "[CALLERIDS]\n";
	print TESTFILE "\n";
	while (($first,$last) = each(%msns)) {
	    chomp($last);
	    if ($last ne "") {
		print TESTFILE "$last\n";
	    }
	}
	print TESTFILE "*       -           *** Unknown ***\n";
	print TESTFILE "\n\n";
	print TESTFILE "# RINGS\n";
	print TESTFILE "#\n";
	print TESTFILE "# Format: TIME DAYS RINGS\n";
	print TESTFILE "\n";
	print TESTFILE "[RINGS]\n";
	print TESTFILE "23:30-23:59,00:00-08:59         *       1\n";
	print TESTFILE "*                               *       6\n";
	print TESTFILE "\n";
	print TESTFILE "# [USERSECTIONS]\n";
	print TESTFILE "#\n";
	print TESTFILE "# Format: TIME DAYS STANDARD RECTIME [FLAG] [...]\n";
	print TESTFILE "\n";
	print TESTFILE "\n";
	foreach $item (@names) {
	    print TESTFILE "[$item]\n";
	    while (($first,$last) = each(%liste)) {
		
		if ($item eq $first) {
		    if ($last ne "") {
			print TESTFILE $last;
		    }
		}
	    }
	}
	print TESTFILE "\n";
	print TESTFILE "[STANDARD]\n";
	print TESTFILE "*       *   standard.msg    20  RINGS=4\n";
	print TESTFILE "\n";

	print TESTFILE "#\n";
	print TESTFILE "# end of generated file\n";
	close(TESTFILE);
    }    
}
#-----------------------------------------------------------------------#
#-------------------------- delete selected action ---------------------#
#-----------------------------------------------------------------------#
sub action_del {
    my $bla = $vboxsecs->curselection();
    $blubb = $vboxsecs->get("$bla");
    $blubb =~ /^([A-Z-]+)/;
    $delete = $1;
    if ($delete eq "STANDARD-OWNER") {
	&errwin("\"STANDARD-OWNER\" is rather important, still want to delete it?","error","YesNo","Error");
	if ($result_button eq "No") {
	    return;
	}
    }
    $vboxsecs->delete("$bla");
    $liste{"$blubb"} = "";
    $msns{"$blubb"} = "";
    $vboxsecs->selectionSet("0");
    foreach $item (@names) {
	unless ($delete eq $item) {
	    push(@names1,$item);
	}
    }
    @names = @names1;
    undef @names1;
    while (($first,$last) = each(%msns)) {
	if ($delete eq $first) {
	    $msns{"$first"} = "";
	}
    }
}
#-----------------------------------------------------------------------#
#-------------------------- edit selected action -----------------------#
#-----------------------------------------------------------------------#
sub action_edit {
    my $bla = $vboxsecs->curselection();
    $blubb = $vboxsecs->get("$bla");
    $blubb =~ /^([A-Z-]+)\s+(\d{3,20})\s+([a-zA-Zs]+)\s+([a-zA-Zs]{0,10})/;
    $edit_id = $1;
    $edit_id2 = $edit_id;
    $edit_msn = $2;
    $edit_name = "$3 $4";
    unless (Exists $added) {
	$maingeometry = $vboxconf->wm("geometry");
	$maingeometry =~ /^(\d{1,3})x(\d{1,3})\+(\d{1,3})\+(\d{1,3})$/;
	$xpos = $3 + 160;
	$ypos = $4 + 120;
	$added        = MainWindow->new();
	$added->wm("title","edit section \"$edit_id\"");
	$added->wm("geometry","+$xpos+$ypos" );
	$framea0 = $added->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$framea1 = $added->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$add_id_l = $framea0->Label(-text => 'ID:')
	    ->pack(-side => 'left');
	$add_id_e = $framea0->Entry(-width => '20',
				    -textvariable => \$edit_id,
				    -bg => 'grey',
				    -state => 'disabled')
	    ->pack(-side => 'left');
	$add_msn_l = $framea0->Label(-text => 'MSN:')
	    ->pack(-side => 'left');
	$add_msn_e = $framea0->Entry(-width => '20',
				     -textvariable => \$edit_msn,
				     -bg => 'white')
	    ->pack(-side => 'left');
	$add_name_l = $framea0->Label(-text => 'Name:')
	    ->pack(-side => 'left');
	$add_name_e = $framea0->Entry(-width => '20',
				      -textvariable => \$edit_name,
				      -bg => 'white')
	    ->pack(-side => 'left');
	$adds_del = $framea1->Button(-text => 'Done',
				     -width => '8',
				     -command => sub {},
				     -font => $defaultfont,
				     -command => sub {$added->destroy()})
	    ->pack(-side => left, -padx => '3');
	$adds_add = $framea1->Button(-text => 'Change',
				     -width => '8',
				     -command => sub {},
				     -font => $defaultfont,
				     -command => \&editsection)
	    ->pack(-side => left, -padx => '3');
    } else {
	$added->raise();
	$added->focus();
    }
}
#-----------------------------------------------------------------------#
#-------------------------- do the actual edit -------------------------#
#-----------------------------------------------------------------------#
sub editsection {
    $edit_id = fillup($edit_id,20);
    $edit_msn = fillup($edit_msn,20);
    $edit_name = fillup($edit_name,20);
    $msns{"$edit_id2"} = "$edit_msn    $edit_id   $edit_name";
    $vboxsecs->delete("$bla");
    $vboxsecs->insert("$bla","$edit_id  $edit_msn  $edit_name");
    $vboxsecs->selectionSet("$bla");
    $added->destroy();
}
#-----------------------------------------------------------------------#
#-------------------------- add a section ------------------------------#
#-----------------------------------------------------------------------#
sub action_add {
    unless (Exists $addsel) {
	$maingeometry = $vboxconf->wm("geometry");
	$maingeometry =~ /^(\d{1,3})x(\d{1,3})\+(\d{1,3})\+(\d{1,3})$/;
	$xpos = $3 + 160;
	$ypos = $4 + 120;
	$addsel        = MainWindow->new();
	$addsel->wm("title","add section \"NEW\"");
	$addsel->wm("geometry","+$xpos+$ypos" );
	$framea0 = $addsel->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$framea1 = $addsel->Frame(-bd => '2', -relief => groove)
	    ->pack(-side => 'top',
		   -expand => 'yes',
		   -fill => 'both',
		   -pady => 7,
		   -padx => 7);
	$add_id_l = $framea0->Label(-text => 'ID:')
	    ->pack(-side => 'left');
	$add_id_e = $framea0->Entry(-width => '10',
				    -textvariable => \$add_id,
				    -bg => 'white')
	    ->pack(-side => 'left');
	$add_msn_l = $framea0->Label(-text => 'MSN:')
	    ->pack(-side => 'left');
	$add_msn_e = $framea0->Entry(-width => '10',
				     -textvariable => \$add_msn,
				     -bg => 'white')
	    ->pack(-side => 'left');
	$add_name_l = $framea0->Label(-text => 'Name:')
	    ->pack(-side => 'left');
	$add_name_e = $framea0->Entry(-width => '30',
				      -textvariable => \$add_name,
				      -bg => 'white')
	    ->pack(-side => 'left');
	$adds_del = $framea1->Button(-text => 'Done',
				    -width => '8',
				    -command => sub {},
				    -font => $defaultfont,
				     -command => sub {$addsel->destroy()})
	    ->pack(-side => left, -padx => '3');

	$adds_ok = $framea1->Button(-text => 'Add',
				    -width => '8',
				    -command => sub {},
				    -font => $defaultfont,
				    -command => sub {&addselection})
	    ->pack(-side => left, -padx => '3');
    } else {
	$addsel->raise();
	$addsel->focus();
    }
}
#-----------------------------------------------------------------------#
#-------------------------- finally add selection ----------------------#
#-----------------------------------------------------------------------#
sub addselection {
    unless ($add_id eq "" || $add_msn eq "") {
	push(@names,$add_id);
	$add_id2 = $add_id;
	$length = length($add_id2);
	$liste{"$add_id"} = "";
	$msns{"$add_id"} = "";
	$add_id = fillup($add_id,20);
	$add_msn = fillup($add_msn,20);
	$add_name = fillup($add_name,20);
	$msns{"$add_id2"} = "$add_msn    $add_id   $add_name";
	$vboxsecs->insert("0","$add_id  $add_msn  $add_name");
	$vboxsecs->selectionSet("0");
	$addsel->destroy();
    } else {
	$addsel->destroy();
	&errwin("You need to add at least \"ID\" and \"MSN\"!","info","OK","Info");
	&action_add;
    }
}
#-----------------------------------------------------------------------#
#-------------------------- well, exit ---------------------------------#
#-----------------------------------------------------------------------#
sub exitvbox {
    system("killall pvftoau 2>/dev/null");
    exit(0);
}
#--------------------------- the END -----------------------------------#
#-----------------------------------------------------------------------#














