#!/usr/local/bin/perl -w
#
#  elmoconf.pl - Configuration tool for Elmo.
#
#  Copyright (C) 2003-2004 Krzysztof Gibas <sdas % gibas org>
#                          rzyjontko
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; version 2.
#
#  This  program is  distributed in the  hope  that  it will be useful,
#  but  WITHOUT  ANY  WARRANTY;  without even  the  implied warranty of
#  MERCHANTABILITY  or  FITNESS  FOR  A  PARTICULAR  PURPOSE.  See  the
#  GNU General Public License for more details.
#
#  You  should  have  received a copy of the GNU General Public License
#  along  with  this  program;  if  not,  write  to  the  Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
#  USA.
#  
#  $Id: elmoconf.pl,v 1.58 2004/03/10 22:23:41 gibas Exp $ 
#  
#  --------------------------------------------------------------------
#
#  This script sets up user's config file based on few simple questions.

use strict;

use constant VERSION => "1.48";


#set secure environment
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/usr/pkg/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

my ($root, $ok, $start, $trash, $drafts, $sent, $outbox, $spam, $localbox, 
    $bayes_file, $guess_email, $editor, $charset, $addressbook, $signature, 
    $smtp_auth_user, $smtp_auth_passwd, $smtp_server, $pop_server, $protect,
    $my_name, $email, $smtp_auth, $username, $password, $pop_info_dir, $theme,
    $ret, $pine, $mutt, $indent_string, $userdomain, $sig_dashes, $elmorc,
    $smtp_ssl, $pop_ssl);

# This function takes 2 arguments.  First is the question (without trailing
# space or ask sign).  Second is the default value.  User will be shown the
# question and asked for a response.  If no answer is supplied, the default
# one will be returned.
sub ask {
    my $question = shift @_;
    my $default  = shift @_;

    print "$question [$default]: ";
    my $response = <STDIN>;
    chomp $response;
    
	if ($response =~ /^(\s*|\t*)$/) {
		return $default;
    }
    return $response;
}

sub ask_passwd {
    my ($response_1, $response_2);
    my $question = shift @_;

    do {
        print "$question: ";
        
        system("stty -echo 2>/dev/null");
        chomp($response_1 = <STDIN>);
        system("stty echo 2>/dev/null");
        print "\n";
        
        print "Re-enter password: ";

        system("stty -echo 2>/dev/null");
        chomp($response_2 = <STDIN>);
        system("stty echo 2>/dev/null");
        print "\n";
        
	if ($response_1 ne $response_2) {
	    print "They don't match; try again.\n";
	}
	
    } while ($response_1 ne $response_2);
    
    return $response_1;
}

# Takes only 1 argument and replaces leading tilde (~) with users home
# directory.
sub replace_tilde {
    $_ = shift @_;

    s/^~/$ENV{HOME}/g;
    return $_;
}

sub have_space {
    $_ = shift @_;

    if (/.*\s+.*/ || length($_) == 0) {
        return "\'$_\'";
    }
    else {
        return $_;
    }
}


sub create_mailbox {
    my $message = shift @_;
    my $dir = shift @_;

    if (is_valid_maildir ("$root/$dir")) {
        print_valid ("$dir");
        return $dir
    }
    elsif (-d "$root/$dir") {
        do {
            print_dir_exists ("$dir");
            $dir = ask ("$message", "$dir");
            $ret = make_maildir ("$root/$dir");
        } while ($ret != 0);

        return $dir;
    }
    elsif (-f "$root/$dir") {
        do {
            print_file_exists ("$dir");
            $dir = ask ("$message", "$dir");
            $ret = make_maildir ("$root/$dir");
        } while ($ret != 0);

        return $dir;
    }
    else {
        do {
            $dir = ask ("$message", "$dir");
            
            while (index ($dir, "/") != -1) {
                print_only_name();
                $dir = ask ("$message", "$dir");
            }
            $ret = make_maildir ("$root/$dir");
        } while ($ret != 0);

        return $dir;
    }
}


sub yes_or_no {
    $_ = shift @_;

    if ($_ =~ /^y(e)?(s)?$/i) {
        return 1;
    }
    else {
        return 0;
    }
}

sub is_valid_maildir {
    my $dir = shift @_;
    
    if (-d $dir && -d "$dir/cur" && -d "$dir/new" && -d "$dir/tmp"){
        return 1;
    }
    else {
        return 0;
    }
}


sub make_maildir {
    my $dir = shift @_;
    my $res;
    
    if (-f $dir) {
        $res = ask("File named $dir already exists. Should I delete it?", "no");
        if (yes_or_no($res)) {
           unlink ($dir) or die "\nCouldn't delete file: $dir: $!\n";
        }
        else {
            return 1;
        }
    }
    if (-d $dir) { 
        $res = ask("Directory named $dir already exists. Should I delete it?", "no");
        if (yes_or_no($res)) {
            system ('rm', '-rf', $dir);
            #system ('rm', '-rf', $dir) or die "\nCouldn't delete directory: $dir: $!\n";
        }
        else {
            return 1;
        }
    }
    
    mkdir ("$dir", 0700) || die "\nCouldn't create $dir: $!\n";
    mkdir ("$dir/new", 0700) || die "\nCouldn't create $dir/new: $!\n";
    mkdir ("$dir/cur", 0700) || die "\nCouldn't create $dir/cur: $!\n";
    mkdir ("$dir/tmp", 0700) || die "\nCouldn't create $dir/tmp: $!\n";
    return 0;
}


sub print_valid {
    my $dir = shift @_;

    print "\nThe directory $dir seems to be a valid maildir.\n";
    print "Using it as a $dir directory.\n\n";
}

sub print_dir_exists {
    my $dir = shift @_;

    print "\nThere is a $dir directory under the specified directory,\n";
    print "but it is not a valid maildir. Maybe another program is using\n";
    print "this directory to store your messages, but using different\n";
    print "format. You will be asked for a box. If $dir is your answer,\n";
    print "it will be destroyed.\n\n"
}

sub print_file_exists {
    my $file = shift @_;

    print "\nThere is a file $file under the specified directory.\n";
    print "You can't use it as a $file because elmo won't be able to\n";
    print "move messages there. You will be asked for a box. If $file\n";
    print "is your answer, it will be removed.\n\n";
}

sub print_only_name {
    print "\nPlease specify only a name of the box under the specified\n";
    print "directory. If it doesn't exist, it will be created for\n";
    print "you. This name must be relative and cannot contain / sign.\n\n";
}


sub local_box {
    my $localbox = shift @_;

    print "\nIt seems that you have a local spool mailbox located at\n";
    print "$localbox. You can read mail delivered to $localbox\n";
    print "with elmo, but there must be a symbolic link created.\n\n";
}


sub print_help {
    print "\nelmoconf.pl - Configuration tool for Elmo.\n\n";
    print "Usage: elmoconf.pl [option]\n\n";
    print "Options:\n";
    print "\t-F | --file <file>\tsave config to given file.\n";
    print "\t-g | --global [file]\tgenerate global config in /etc/elmorc\n";
    print "\t-h | --help\t\tprints this help\n";
    print "\t-M | --muttrc [file]\ttry to extract some variables from your ~/.muttrc\n";
    print "\t-p | --pop\t\tadd new pop3 account to config\n";
    print "\t-P | --pinerc [file]\ttry to extract some variables from your ~/.pinerc\n";
    print "\t-s | --smtp\t\tadd new smtp account to config\n";
    print "\t-V | --version\t\tshows version\n\n";
    exit 0;
}

sub print_version {
    print "elmoconf.pl-" . VERSION . "\n";
    exit 0;
}

sub get_smtp_info {
    if ($guess_email) {
        $guess_email = $guess_email;
    } 
    elsif ($ENV{EMAIL}) {
        $guess_email = $ENV{EMAIL};
    }
    elsif ($ENV{USER} && $userdomain) {
        $guess_email = "$ENV{USER}" . "\@" . $userdomain;
    }
    elsif ($ENV{USER} && ($userdomain = `hostname`)) {
	chomp($userdomain);
	$guess_email = "$ENV{USER}" . "\@" . $userdomain;
    }
    elsif ($ENV{USER} && $ENV{HOSTNAME}) {
        $guess_email = "$ENV{USER}" . "\@" . "$ENV{HOSTNAME}";
    }
    elsif ($ENV{USER} && $ENV{HOST}) {
        $guess_email = "$ENV{USER}" . "\@" . "$ENV{HOST}";
    }
    else {
        $guess_email = "";
    }

    if ($my_name) {
        $my_name = ask ("What is your name", "$my_name");
    }
    else {
        $my_name = ask ("What is your name", "$ENV{USER}");
    }

    $email = ask ("What is your email", "$guess_email");

    if ($smtp_server) {
        $smtp_server = ask ("What is your smtp server", "$smtp_server");
    }
    elsif ($ENV{HOSTNAME}) {
        $smtp_server = ask ("What is your smtp server", "$ENV{HOSTNAME}");
    }
    elsif ($ENV{HOST} && !$ENV{HOSTNAME}) {
        $smtp_server = ask ("What is your smtp server", "$ENV{HOST}");
    }
    elsif ($userdomain = `hostname`) {
	chomp($userdomain);
	$smtp_server = ask ("What is your smtp server", $userdomain);
    }	         
    else{
        $smtp_server = ask ("What is your smtp server", "");
    }

    $smtp_auth   = ask ("Should I use smtp auth for your account", "yes");

    if (yes_or_no($smtp_auth)) {
        $smtp_auth_user  = ask ("What is your smtp auth username", "$ENV{USER}");
        $smtp_auth_passwd = ask_passwd ("What is your smtp auth password");
    }
    else {
        $smtp_auth_user = $ENV{USER};
        $smtp_auth_passwd = "";
    }

    $smtp_ssl = ask ("Do you want to use ssl", "no");
    
}

sub write_smtp_info {
    print CONFIG "set smtp_acc {\n  name: " . have_space($smtp_server) . "\n  server: " . have_space($smtp_server) . "\n";
    print CONFIG "  my_name: " . have_space($my_name) . "\n  email: " . have_space($email) . "\n  port: 25\n";

    if (yes_or_no($smtp_auth)) {
        print CONFIG "  username: " . have_space($smtp_auth_user) . "\n";
        print CONFIG "  password: " . have_space($smtp_auth_passwd) . "\n";
    }
    
    if ($smtp_ssl) {
            print CONFIG "  ssl: " . have_space($smtp_ssl) . "\n";
    }
    
    print CONFIG "\}\n\n";    
}

sub get_pop_info {
    if ($pop_server) {
        $pop_server = ask ("What is your pop3 server", "$pop_server");
    }
    elsif ($ENV{HOSTNAME}) {
        $pop_server = ask ("What is your pop3 server", "$ENV{HOSTNAME}");
    }
    elsif ($ENV{HOST}) {
        $pop_server = ask ("What is your pop3 server", "$ENV{HOST}");
    }
    elsif ($userdomain = `hostname`) {
	chomp($userdomain);

	$pop_server = ask ("What is your pop3 server", $userdomain);
    }
    else{
        $pop_server = ask ("What is your pop3 server", "");
    }

    if ($username) {
        $username = ask ("What is your pop3 username", "$username");
    }
    else {
        $username = ask ("What is your pop3 username", "$ENV{USER}");
    }
    
    $password = ask_passwd ("What is your pop3 password");

    $pop_ssl = ask("Do you want to use ssl", "no");
}

sub write_pop_info {
    print CONFIG "set pop_acc {\n  name: " . have_space($pop_server) . "\n  server: " . have_space($pop_server) . "\n";
    print CONFIG "  username: " . have_space($username) . "\n  password: " . have_space($password) . "\n  port: 110\n";
    print CONFIG "  count_max: 0\n";
    
    if ($pop_ssl) {
        print CONFIG "  ssl: " . have_space($pop_ssl) . "\n";
    }
    
    print CONFIG "}\n\n";
}

sub write_mailbox {
    print CONFIG "set mailbox {\n  name: 'mail'\n  root: " . have_space($root) . "\n";
    print CONFIG "  start: " . have_space($start) . "\n  drafts: " . have_space($drafts) . "\n";
    print CONFIG "  trash: " . have_space($trash) . "\n  sent: " . have_space($sent) . "\n";
    print CONFIG "  outbox: " . have_space($outbox) . "\n  spam: " . have_space($spam) . "\n";
    print CONFIG "  protect: " . have_space($protect) . "\n}\n\n";
}

sub write_sigfile {
    print CONFIG "set sigfile " . have_space($signature) . "\n";
}

sub write_editor {
    print CONFIG "set editor \'$editor \%f\'\n";
}

sub write_addressbook {
    print CONFIG "set addressbook " . have_space($addressbook) . "\n";
}

sub write_pop_infodir {
    print CONFIG "set pop_info_dir " . have_space($pop_info_dir) . "\n\n";
}

sub write_bayes_file {
    if ($bayes_file and yes_or_no($protect)) {
        print CONFIG "set bayes_file " . have_space($bayes_file) . "\n";
    }
}

sub write_other {
    
    #indent_string
    if ($indent_string) {
        print CONFIG "set indent_string \'$indent_string\'\n";
    }
    else {
        print CONFIG "set indent_string '> '\n";
    }
    
    #sig_dashes
    if ($sig_dashes and yes_or_no($sig_dashes)) {
        print CONFIG "set sig_dashes on\n";
    }
    else {
        print CONFIG "set sig_dashes off\n";
    }

    print CONFIG "#set welcome_msg no\n";
    print CONFIG "set relative_names on\n\n";
}

sub write_formats {
    print CONFIG "#set line_format \'\%\?\%\$\%\# \%D \%016f \(\%\-06S\)  \'\n";
    print CONFIG "#set sent_format \'\%\?\%\$  \%D \%016t \(\%-06S\)  \'\n";
    print CONFIG "#set abook_format \'\%s \%020n \%e\'\n";
    print CONFIG "#set win_fetch {\n\#\tfetch_fmt: \'\%\?\%\$  \%D \%016f \(\%-06S\)  \%s\'\n\#}\n";
    print CONFIG "#set win_help {\n\#\thelp_fmt: \'\%012k \%030f \%d\'\n\#}\n";
    print CONFIG "#set win_boxes {\n\#\tbox_fmt: \' \%010n \(\%u\/\%t\)\'\n\#}\n";
    print CONFIG "#set win_attach {\n\#\tattach_fmt: \'\%020f \(\%-06s\) [\%t\%C\%E]\'\n\#}\n";
    print CONFIG "#set win_sender {\n\#\tsender_fmt: \'\%020f \(\%-06s\) [\%t\%C\%E]\'\n\#}\n\n";
}


sub get_charset {
    my %LANG = (
                "ca_ES" => "iso-8859-1",
                "cs_CZ" => "iso-8859-2",
                "da_DK" => "iso-8859-1",
                "de_DE" => "iso-8859-1",
                "el_GR" => "iso-8859-7",
                "es_ES" => "iso-8859-1",
                "et_EE" => "iso-8859-1",
                "fi_FI" => "iso-8859-1",
                "fr_FR" => "iso-8859-1",
                "gl_ES" => "iso-8859-1",
                "he_IL" => "iso-8859-8",
                "hr_HR" => "iso-8859-2",
                "hu_HU" => "iso-8859-2",
                "is_IS" => "iso-8859-1",
                "it_IT" => "iso-8859-1",
                "lt_LT" => "iso-8859-13",
                "nl_NL" => "iso-8859-1",
                "nn_NO" => "iso-8859-1",
                "no_NO" => "iso-8859-1",
                "pl_PL" => "iso-8859-2",
                "pt_PT" => "iso-8859-1",
                "ro_RO" => "iso-8859-2",
                "ru_RU" => "iso-8859-5",
                "sk_SK" => "iso-8859-2",
                "sl_SI" => "iso-8859-2",
                "sv_SE" => "iso-8859-1",
                "tr_TR" => "iso-8859-9",
                "us_US" => "US_ASCII"
        );

    if ($charset) {
        #huh... from .pinerc or .muttrc.
        $charset = $charset;
    } 
    elsif (($ENV{LANG} && $ENV{LANG} eq 'C') || ($ENV{LC_ALL} && $ENV{LC_ALL} eq 'C') || ($ENV{LC_CTYPE} && $ENV{LC_CTYPE} eq 'C')) {
        $charset = "US-ASCII";
    }
    elsif ($ENV{LC_ALL} and exists ($LANG{"$ENV{LC_ALL}"})) {
        $charset = $LANG{"$ENV{LC_ALL}"};
    }
    elsif ($ENV{LC_CTYPE} and exists ($LANG{"$ENV{LC_CTYPE}"})) {
        $charset = $LANG{"$ENV{LC_CTYPE}"};
    }
    elsif ($ENV{LANG} and exists ($LANG{"$ENV{LANG}"})) {
        $charset = $LANG{"$ENV{LANG}"};
    }
}

sub write_charset {
    $charset =~ tr/ISO/iso/;

    print CONFIG "set charset " . have_space($charset) . "\n";
    print CONFIG "translate utf-8 " . have_space($charset) . "\n";

    if ($charset =~ /^iso-8859-2$/) {
        print CONFIG "translate windows-1250 iso-8859-2\n";
    }
}

sub get_theme {
    print "Themes:\n";
    print "\t80x25 - simple, created for 80x25 consoles.\n";
    print "\toutlook - looks nice on framebuffer console.\n";
    $theme = ask ("What theme do you choose", "default");
}

sub write_theme {
my $theme_80x25 = "# Theme: 80x25\n# Author: rzyjontko\n#
# This theme is recommended for people using standard console, which
# is 80 colums wide, and 25 lines high.  You will lose some
# information displayed in windows but they will all fit on your
# screen.\n
set line_format \"\%\$ \%D \%014f (\%-06S) \"\n
set sent_format \"\%\$ \%D \%014f (\%-06S) \"\n
set win_frames \{\n\tfill:\"(15 0 15 0)\"\n\tf_horiz: \"(0 -6 14 -6)\"\n\tf_vert: \"(15 1 15 -1)\"\n\tf_left: \"(15 -6 15 -6)\"\n}\n
set win_clock \{\n\twidth: 15\n\theight: 5\n\ttop: -7\n\tclock_fmt: \" \%H:\%M \%e \%b \"\n}\n
set win_folder \{\n\twidth: -16\n\tleft: 16\n}\n
set win_boxes \{\n\twidth: 15\n\theight: -10\n\tbox_fmt: \" \%010n\"\n}\n
set win_fetch \{\n\tfetch_fmt: \"\%\$ \%D \%014f (\%-06S) \"\n}";

my $theme_outlook = "# Theme: outlook\n# Authors: rzyjontko, Krzysztof Gibas\n#
# This theme tries to make elmo look like most of mail clients for
# window systems.  I don't recommend this theme for small terminals
# (like standard 80x25).\n
set win_folder {\n\theight: 15\n}\n
set win_mail {\n\tleft:    26\n\ttop:     18\n\theight: -20\n\twidth:  -26\n\tlabel: 1\n}\n
set win_boxes {\n\theight: 15\n}\n
set win_frames {\n\tfill:    \"(25 0 25 0) (25 16 25 16)\"\n\tf_horiz: \"(0 -8 24 -8)\"\n\tf_left:  \"(25 -8 25 -8)\"\n}\n
set win_attach {\n\tleft:   26\n\twidth: -26\n}\n
set win_abook {\n\theight: -28\n\twidth: 25\n\ttop: 18\n\tleft: 0\n\tlabel: 1\n\tabook_fmt: \" %020n\"\n}\n
key mail q cmd_quit\nkey abook q cmd_nothing\n\nhook cmd_after_startup abook_show\nhook cmd_after_startup mailreader_load
hook cmd_after_startup interface_next_window\nhook folder_at_bar_move mailreader_load\n";

    if ($theme ne "default") {
        if (! -e "$root/.themes") {
            mkdir("$root/.themes", 0700) || die "\nCouldn't create $root/.themes: $!\n"
        }
        
        if (! -e "$root/.themes/80x25" && $theme eq "80x25") {
            open (THEME, ">$root/.themes/$theme") || die "\nCouldn't create theme $theme: $!\n";
            flock (THEME, 2) || die "\nCouldn't lock file theme $theme: $!";
            
                print THEME $theme_80x25;
            
            close (THEME) || print "\nCouldn't close theme file: $!\n";
        
			print CONFIG "\n#theme - $theme\n";
			print CONFIG "include $root/.themes/$theme\n\n";
		}

        if (! -e "$root/.themes/outlook" && $theme eq "outlook") {
            open (THEME, ">$root/.themes/$theme") || die "\nCouldn't create theme $theme: $!\n";
            flock (THEME, 2) || die "\nCouldn't lock file theme $theme: $!";

                print THEME $theme_outlook;

            close (THEME) || print "\nCouldn't close theme file: $!\n";
	    
			print CONFIG "\n#theme - $theme\n";
			print CONFIG "include $root/.themes/$theme\n\n";
        }
    }
}

sub write_key_bindings {
    print CONFIG "#KEY BINDINGS\n";
    print CONFIG "key mail r sender_open_reply\n";
    print CONFIG "key mail f sender_open_fwd\n";
    print CONFIG "key mail R sender_open_reply_all\n\n";
}

sub write_hooks {
    print CONFIG "#HOOKS\n";
    print CONFIG "hook folder_toggle_flag folder_bar_next\n";
    print CONFIG "hook fetch_del_mail fetch_next\n";
    print CONFIG "hook fetch_get_mail fetch_next\n";
    print CONFIG "hook mybox_create_box box_selection_re_read\n";
    print CONFIG "hook sender_go mailreader_close\n\n";
    print CONFIG "#AUTOSEND\n";
    print CONFIG "#hook sender_go smtp_flush_outbox\n\n";
    print CONFIG "hook abook_hit abook_next\n\n";
}

sub check_config_exists {
    my $file = shift @_;
    
    if (-e "$file") {
        print "\nFound existing $file. The existing file will be\n";
        print "renamed to $file.0.\n\n";
        rename "$file", "$file.0";
    }
}

sub create_local_box {
    my $box = shift @_;
    
    local_box ($box);
    
    $localbox = ask ("How do you want to name your local box", "local");
        
    if (-e "$root/$localbox") {
        print "\nError: File $root/$localbox exists.\n\n";
    }
    else {
        symlink ("$box", "$root/$localbox") or print "Error: $!\n";
    }
}

sub tutorial {
    my $box_root = shift @_;
    my $prefix;
    my $dir;
    my @prefix = ("/usr", "/usr/local", "/usr/pkg");
    my @dir = ("share/doc/elmo", "share/elmo");

    foreach $prefix (@prefix) {
	foreach $dir (@dir) {
	    if ( -e "$prefix/$dir/tutorial" && ! -e "$box_root/tutorial") {
		symlink("$prefix/$dir/tutorial", "$box_root/tutorial");
	    }
	}
    }
}


sub extract_from_line {
    my $line = shift @_;
    my (@parts, @part);

    @parts = split(/=/, $line);
    
    chomp($parts[1]);
    
    if ($parts[1] =~ /^\".*\"$/) {
        @part = split (/\"/, $parts[1]);
	return $part[1];
    }
    else {
	return $parts[1];
    }
}
															    

sub mutt2elmo {
    my $rcfile = shift @_ || "$ENV{HOME}/.muttrc";
    
    my $linia;

    open(FILE, "<$rcfile") or die "Error: can\'t open $rcfile: $!\n";	
    flock (FILE, 1) || die "\nCouldn't lock file $rcfile: $!";
    my @line = <FILE>;

    foreach $linia(@line) {
	#jeżeli linia nie jest komentarzem.
	if ($linia !~ /^\s*#.*$/) {
            if ($linia =~ /^set\s+editor=\"?.*\"?$/) {
                $editor = extract_from_line($linia);
            }
            elsif ($linia =~ /^set\s+signature=\"?.*\"?$/) {
                $signature = extract_from_line($linia);
            }
            elsif ($linia =~ /^set\s+pop_host=\"?.*\"?$/) {
                $pop_server = extract_from_line($linia);
            }
            elsif ($linia =~ /^set\s+pop_user=\"?.*\"?$/) {
                $username = extract_from_line($linia);
            }
            elsif ($linia =~ /^set\s+realname=\"?.*\"?$/) {
                $my_name = extract_from_line($linia);
            }
            elsif ($linia =~ /^set\s+from=\"?.*\"?$/) {
                $guess_email = extract_from_line($linia);
            }
            elsif ($linia =~ /^set\s+indent_string=\"?.*\"?$/) {
                $indent_string = extract_from_line($linia);
            }
            elsif ($linia =~ /^set\s+hostname=\"?.*\"?$/) {
                $userdomain = extract_from_line($linia);
            }
            elsif ($linia =~ /^set\s+charset=\"?.*\"?$/) {
                $charset = extract_from_line($linia);
            }
            elsif ($linia =~ /^set\s+sig_dashes=\"?.*\"?$/) {
                $sig_dashes = extract_from_line($linia);
            }
            
            #elsif ($linia =~ /^set\s+pop_pass=\"?.*\"?$/) {
            #    $password = extract_from_line($linia);
            #}

            #extract_from_file("mutt", "attribution", $linia);
            #extract_from_file("mutt", "folder", $linia);
            #extract_from_file("mutt", "help", $linia);
	    #extract_from_file("mutt", "locale", $linia);
	    #extract_from_file("mutt", "mbox", $linia);
	    #use_8bitmime
        }
    }
    close(FILE) or print "\nCouldn't close $rcfile: $!\n";
}

sub pine2elmo {
    my $rcfile = shift @_ || "$ENV{HOME}/.pinerc";
    
    my $linia;

    open(FILE, "<$rcfile") or die "Error: can\'t open $rcfile: $!\n";
    flock (FILE, 1) || die "\nCouldn't lock file $rcfile: $!";
    my @line = <FILE>;

    foreach $linia(@line) {
	#jeżeli linia nie jest komentarzem.
	if ($linia !~ /^\s*#.*$/) {
            if ($linia =~ /^\s*character-set=\"?.*\"?$/) {
                $charset = extract_from_line($linia);
            }
            if ($linia =~ /^\s*editor=\"?.*\"?$/) {
                $editor = extract_from_line($linia);
            }
            elsif ($linia =~ /^\s*signature-file=\"?.*\"?$/) {
                $signature = extract_from_line($linia);
            }
            elsif ($linia =~ /^\s*personal-name=\"?.*\"?$/) {
                $my_name = extract_from_line($linia);
            }
            elsif ($linia =~ /^\s*smtp-server=\"?.*\"?$/) {
                $smtp_server = extract_from_line($linia);
            }
	        elsif ($linia =~ /^\s*reply-indent-string=\"?.*\"?$/) {
                $indent_string = extract_from_line($linia);
            }
            elsif ($linia =~ /^\s*user-domain=\"?.*\"?$/) {
                $userdomain = extract_from_line($linia);
	    }
        }
    }
    close(FILE) or print "\nCouldn't close $rcfile: $!\n";;
}

# STEP 0
# PROGRAM PARAMETRS
if (@ARGV >= 1) {
    my ($globalrc, $force);

    if ($ARGV[0] eq '--global' or $ARGV[0] eq '-g') {
        #generate global config in /etc/elmorc
        
        if ($ARGV[1]) {
            if ($ARGV[1] eq '--force' or $ARGV[1] eq '-f') {
                $force = 1;
                $globalrc = "/etc/elmorc";
            }
            else {
                $globalrc = $ARGV[1];
            }
        }
        elsif ($ARGV[2]) {
            $globalrc = $ARGV[2];
        }
        else {
            $globalrc = "/etc/elmorc";
        }
        
        
        if (-e $globalrc) {    
            print "\nFound existing $globalrc file. New config will be saved\n";
            print "in $globalrc.new\n\n";
            
            #ask only if parametr --force isn't set.
            if ( -e "$globalrc.new" and !$force) {
                $ret = ask("Ooops! File $globalrc.new exists! Should I overwrite it?", "yes");
                if (! yes_or_no($ret)) {
                   exit 0; 
                }
            }
            $globalrc = $globalrc . ".new";
        }
        
        open (CONFIG, ">$globalrc") || die "\nCouldn't create $globalrc: $!\n";
        flock (CONFIG, 2) || die "\nCouldn't lock file $globalrc: $!";
        
            $root = "~/mail";
            $start = "inbox";
            $drafts = "drafts";
            $trash = "trash";
            $sent = "sent";
            $outbox = "outbox";
            $spam = "spam";
            $protect = "yes";
            write_mailbox();
 
            $smtp_server = "localhost";
            $my_name = "\$USER";
            $email = "\$USER\@\$HOSTNAME";        
            $smtp_auth = "no";
            write_smtp_info();
            
            $bayes_file = "~/mail/.bayes_file";
            write_bayes_file();
        
            $addressbook = "~/mail/.addressbook";
            write_addressbook();
        
            $pop_info_dir = "~/mail/.pop";
            write_pop_infodir();

            $signature = "~/.signature";
            write_sigfile();

            $editor = "\$EDITOR";
            write_editor();
        
            write_other();

            # CHARSET
            get_charset();

            if (! $charset) {
                $charset = "iso-8859-1";
            }
            write_charset();
        
            # KEY BINDINGS
            write_key_bindings();

            # HOOKS
            write_hooks(); 
    
        close (CONFIG) || print "\nCouldn't close $globalrc: $!\n";
        chmod (0644, "$globalrc") or print "\nCouldn't chmod $globalrc: $!\n";        
        exit 0;
    }
    elsif ($ARGV[0] eq '--help' or $ARGV[0] eq '-h') {
        #shows help.
        print_help();
    }
    elsif ($ARGV[0] eq '--pop' or $ARGV[0] eq '-p') {
        #add new pop3 account.
        get_pop_info();
        
        open (CONFIG, ">>$ENV{HOME}/.elmorc") || die "\nCouldn't add to file $ENV{HOME}/.elmorc: $!\n";
        flock (CONFIG, 2) || die "\nCouldn't lock file $ENV{HOME}/.elmorc: $!";
        
        write_pop_info();
        
        close (CONFIG) || print "\nCouldn't close file: $!\n";
        chmod (0600, "$ENV{HOME}/.elmorc") or die "\nCouldn't chmod $ENV{HOME}/.elmorc: $!\n";
        
        exit 0;
    }
    elsif ($ARGV[0] eq '--smtp' or $ARGV[0] eq '-s') {
        #add new smtp account.
        get_smtp_info();

        open (CONFIG, ">>$ENV{HOME}/.elmorc") || die "\nCouldn't add to file $ENV{HOME}/.elmorc: $!\n";
        flock (CONFIG, 2) || die "\nCouldn't lock file $ENV{HOME}/.elmorc: $!";
        
        write_smtp_info();
        
        close (CONFIG) || print "\nCouldn't close file: $!\n";
        chmod (0600, "$ENV{HOME}/.elmorc") or die "\nCouldn't chmod $ENV{HOME}/.elmorc: $!\n";

        exit 0;
    }
    elsif ($ARGV[0] eq '--muttrc' or $ARGV[0] eq '-M') {
        if ($ARGV[1]) {
			mutt2elmo($ARGV[1]);
        }
        else {
            mutt2elmo();
        }
        $mutt = 1;
    }   
    elsif ($ARGV[0] eq '--pinerc' or $ARGV[0] eq '-P') {
	if ($ARGV[1]) {
            pine2elmo($ARGV[1]);
        }
        else {
            pine2elmo();
        }
        $pine = 1;
    }
    elsif ($ARGV[0] eq '--version' or $ARGV[0] eq '-V') {
        #show version
        print_version();
    }
    elsif ($ARGV[0] eq '--file' or $ARGV[0] eq '-F') {
        if ($ARGV[1]) {
	    $elmorc = $ARGV[1];
        }
        else {
            print "elmoconf.pl: Option $ARGV[0] need file name.\n";
            print "Try `elmoconf.pl --help' for more information.\n";
            exit 0;
        }
    }
    else {
        print "elmoconf.pl: unrecognized option \`" . $ARGV[0] . "\'\n";
        print "Try `elmoconf.pl --help' for more information.\n";
        exit 0;
    }
}


# TRY TO EXTRACT VARIABLES FROM .muttrc or .pinerc
if (-e "$ENV{HOME}/.muttrc" and !$mutt) {
    mutt2elmo();
}
elsif (-e "$ENV{HOME}/.pinerc" and !$pine) {
    pine2elmo();
}


# STEP 1
# Set up root directory of mailbox.
do {
    $root = ask ("Where do you want to store your mailboxes", "~/mail");
    $root = replace_tilde ($root);

    if (-d $root) {
		$ok = 1;
    }
    elsif (! -e $root) {
        mkdir ($root, 0700) || die "\nCouldn't create $root: $!\n";
        $ok = 1;
    }
    else {
	print "\nYou have specified an existing file to be a location\n";
	print "of your mailboxes collection. I'm afraid it's impossible.\n";
	print "Elmo stores your mailboxes in a single directory.\n\n";
	print "Please specify a directory name.\n\n"
    }
} while (! $ok);


# STEP 2
# Start box.
$start = create_mailbox("What is your start box", "inbox");
    
# STEP 3
# Trash.
$trash = create_mailbox("Where do you want to move deleted messages", "trash");

# STEP 4
# Drafts.
$drafts = create_mailbox("Where do you want to store your unfinished messages", "drafts");

# STEP 5
# Sent.
$sent = create_mailbox("Where do you want to store your sent messages", "sent");

# STEP 6
# Outbox
$outbox = create_mailbox("Where do you want to store your outbox messages", "outbox");

# STEP 7
# Spam.
$spam = create_mailbox("Where do you want to store your spam messages", "spam");

# STEP 8
# Existing spool mailboxes
if ($ENV{MAILDIR} && -e $ENV{MAILDIR}) {
    create_local_box($ENV{MAILDIR});
}

if ($ENV{MAIL} && -e $ENV{MAIL}) {
    create_local_box($ENV{MAIL});
}

# STEP 9
# MAILBOX WITH TUTORIAL
tutorial($root);

# STEP 10
# SMTP
my $answer_smtp = ask("Do you want to configure smtp account?", "yes");
if (yes_or_no($answer_smtp)) {
    get_smtp_info();
}


# STEP 11
# POP3
my $answer_pop = ask("Do you want to configure pop3 account?", "yes");
if (yes_or_no($answer_pop)) { 
    get_pop_info();
}

# STEP 12
# SPAM PROTECTION
$protect = ask ("Should I protect your mail against spam", "yes");

if (yes_or_no($protect)) {
    $bayes_file  = "$root/.bayes_file";
    
    #if (! -e $bayes_file) {
    #	open(BAYESFILE, ">$bayes_file") or print "\nCouldn't create $bayes_file: $!\n";
    #       print BAYESFILE "";
    #	close(BAYESFILE) or print "\nCouldn't close $bayes_file: $!\n";
    #}
}

# STEP 13
# ADDRESSBOOK
$addressbook = ask ("Where do you want store your addressbook", "$root/.addressbook");
$addressbook = replace_tilde($addressbook);

if (! -e $addressbook) {
    open(ADDRESSBOOK, ">$addressbook") or print "\nCouldn't create $addressbook: $!\n";
    flock (ADDRESSBOOK, 2) or print "\nCouldn't lock file $addressbook: $!";
        print ADDRESSBOOK "";
    close(ADDRESSBOOK) or print "\nCouldn't close $addressbook: $!\n";
}

# STEP 14
# EDITOR
if ($editor) {
    $editor = ask ("What is your favorite editor", $editor);
}
elsif ($ENV{EDITOR}) {
    $editor = ask ("What is your favorite editor", "$ENV{EDITOR}");
}
else {
    $editor = ask ("What is your favorite editor", "vim");
}
  
# STEP 15
# SIGNATURE
if ($signature) {
    $signature = ask ("Where is your signature file", "$signature");
}    
else {
    $signature = ask ("Where is your signature file", "$ENV{HOME}/.signature");
}
$signature = replace_tilde($signature);

# STEP 16
# CHARSET
get_charset();

if ($charset) {
    $charset = ask ("What is your charset", "$charset");
}
else {
    $charset = ask ("What is your charset", "iso-8859-1");
}

# STEP 17
# THEMES
get_theme();

# STEP 18
# POP_INFO_DIR
if (! -d "$root/.pop") {
    mkdir ("$root/.pop", 0700) || print "\nCouldn't create pop_info_dir - $root/.pop: $!\n";
}
$pop_info_dir = "$root/.pop";


# STEP 19
# WRITE TO CONFIG

$elmorc = $elmorc || "$ENV{HOME}/.elmorc";

check_config_exists("$elmorc");

open (CONFIG, "> $elmorc") || die "\nCouldn't create $elmorc: $!\n";
flock (CONFIG, 2) || die "\nCouldn't lock file $elmorc: $!";

    write_mailbox();

    if (yes_or_no($answer_smtp)) { 
        write_smtp_info();
    }

    if (yes_or_no($answer_pop)) {
        write_pop_info();
    }
    
    write_pop_infodir();

    write_bayes_file();

    write_addressbook();

    write_sigfile();

    write_editor();

    write_charset();

    write_theme();

    write_other();

    # FORMATS
    write_formats();

    # KEY BINDINGS
    write_key_bindings();

    # HOOKS
    write_hooks();

close (CONFIG) || print "\nCouldn't close file $elmorc: $!\n";

chmod (0600, "$elmorc") or die "\nCouldn't chmod $elmorc: $!\n";



syntax highlighted by Code2HTML, v. 0.9.1