#!/usr/bin/perl --
# Copyright 1998,1999 Ivan E. Moore II
# See /usr/share/doc/imp/copyright.
$|=1;

$etc='/etc/imp';
$syshostname=`hostname --fqdn`;
chop($syshostname=`hostname --fqdn`);

if (-s "/usr/sbin/apache-ssl") {
  $srm='/etc/apache-ssl/srm.conf';  
  $http='/etc/apache-ssl/httpd.conf';
} else {
  $srm='/etc/apache/srm.conf';
  $http='/etc/apache/httpd.conf';
}


  if (-s "/usr/bin/psql") {
    $database='postgres';
  } else {
    if (-s "/usr/bin/mysql") {
      $database='mysql';
     } else {
      $database='dummy';
     }
  }

  $php='/etc/php3/apache/php3.ini';
  $tmproot='/var/www';
  $buildopts ='/etc/imp/build.opts';

sub loadconf ($$;$)
{
    $parameter = 'DocumentRoot';
    $default = $_[1];

    $file = (defined ($_[2]) ? $_[2] : "$http");
    $in = `egrep "^[:space:]*$parameter " $file 2> /dev/null| head -1`;
    $in =~ s/\s*$parameter //;
    chomp ($in);
    return $in if ($in ne "");
    return $default;
}

sub load_conf ($$;$)
{
    my $parameter = $_[0];
    my $default = $_[1];

    my $file = (defined ($_[2]) ? $_[2] : "$srm"); 
    my $in = `egrep "^[:space:]*$parameter " $file 2> /dev/null| head -1`;
    $in =~ s/\s*$parameter //;
    chomp ($in);              
    return $in if ($in ne "");   
    return $default;              
}

sub load_php_conf ($$;$)
{
    my $parameter = $_[0];
    my $default = $_[1];

    my $file = (defined ($_[2]) ? $_[2] : "$php");
    my $in = `egrep "^[:space:]*$parameter " $file 2> /dev/null| head -1`;
    $in =~ s/\s*$parameter //;
    chomp ($in);
    return $in if ($in ne "");
    return $default;
}


$install_dir = loadconf ("DocumentRoot", $tmproot, $srm);


sub load_config_files ()
{
    $main::srmconf = `cat $srm`;
    $main::dirindex = load_conf ("DirectoryIndex",$tmpdirindex, $srm);
    $main::phpconf = `cat $php`;
    $main::buildconf = (-f $buildopts ? `cat $buildopts`: '');

}


$write_srmconf = 0;
$write_phpconf = 0;
$restart_apache = 0;
$write_buildconf = 0;

sub make_corrections ()
{
    if (! ($srmconf =~ m/.*Alias\s+\/imp\/\s+\/usr\/share\/horde\/imp\//m))
    {
        print "Adding alias /imp/ -> /usr/share/horde/imp/ to srm.conf.\n";
        $srmconf =~ s/$/\n# Added for IMP\n/s;
        $srmconf =~ s/$/Alias \/imp\/ \/usr\/share\/horde\/imp\/\n/s;
    if (! ($srmconf =~ m/.*Alias\s+\/imp\s+\/usr\/share\/horde\/imp\//m))
    {
        $srmconf =~ s/$/Alias \/imp \/usr\/share\/horde\/imp\/\n/s;
    }
        $write_srmconf++;
    }
    if (! ($phpconf =~ m/.*extension=imap.so/m))
    {
        print "Adding extension=imap.so to php3.ini\n";
        $phpconf =~ s/$/\n;  Added for use with IMP \n/s;
        $phpconf =~ s/$/extension=imap.so\n/s;
        $write_phpconf++;
    }
    if (! ($phpconf =~ m/.*extension=mysql.so/m))
    {
        print "Adding extension=mysql.so to php3.ini\n";
        $phpconf =~ s/$/extension=mysql.so\n/s;
        $write_phpconf++;
    }
    if (! ($phpconf =~ m/.*extension=pgsql.so/m))
    {
        print "Adding extension=pgsql.so to php3.ini\n";
        $phpconf =~ s/$/extension=pgsql.so\n/s;
        $write_phpconf++;
    }
    if (! ($phpconf =~ m/.*extension=ldap.so/m))
    {
        print "Adding extension=ldap.so to php3.ini\n";
        $phpconf =~ s/$/extension=ldap.so\n/s;
        $write_phpconf++;
    }

  if (! ($database =~ dummy)) {
    if ($buildconf =~ m/.*--with-database=*/m)
    {
       system("rm /etc/horde/imp/build.opts >> /dev/null 2>&1");
       system("touch /etc/horde/imp/build.opts >> /dev/null 2>&1");
    }
    if (! ($buildconf =~ m/.*database=*/m))
    {
        print "Setting $database as your database option in build.opts\n";
        $buildconf =~ s/$/database=$database\n/s;
        $write_buildconf++;
    }
  }
}

if (! (-s "/etc/horde/imp/defaults.php3")) {
  load_config_files ();
  make_corrections ();
}

if (-s "/etc/horde/config") {
  $have_imp = `cat /etc/horde/config | grep imp`;
  if ($have_imp)  {
     print "\n";
} else {
     system ("echo 'imp\n' >> /etc/horde/config");
  }
}


if ($write_buildconf)
{
    system ("savelog -c 100 $buildopts >> /dev/null 2>&1")
        && die ("couldn't rotate $buildopts\n");
    open (CONF, ">$buildopts") || die ("couldn't open $buildopts\n");
    print CONF $buildconf;
    close (CONF);
}

if ($write_srmconf)
{
    system ("savelog -c 100 $srm >> /dev/null 2>&1")
        && die ("couldn't rotate $srm");
    open (CONF, ">$srm") || die ("couldn't open $srm");
    print CONF $srmconf;
    close (CONF);
    $restart_apache++;
}

if ($write_phpconf)
{
    system ("savelog -c 100 $php >> /dev/null 2>&1")
        && die ("couldn't rotate $php");
    open (CONF, ">$php") || die ("couldn't open $php");
    print CONF $phpconf;
    close (CONF);     
    $restart_apache++; 
}

if (-s "/etc/horde/imp/defaults.php3") {

system("chmod -R 644 /usr/share/horde/lib/*.lib >> /dev/null 2>&1");
system("chmod -R 644 /usr/share/horde/imp/lib/*.lib >> /dev/null 2>&1");

### Configure IMP Libraries ###

   print "
Building IMP Libraries for your specific installation
";


## Build the libraries ##

    system("cd /usr/share/horde/imp/lib/src && ./build.pl --with-config=/etc/horde/imp/build.opts >> /dev/null 2>&1");

## Move old config file back ##
   system("cp /etc/horde/imp/defaults.php3.bak /etc/horde/imp/defaults.php3 >> /dev/null 2>&1");

### Change file permissions for security ###

 system("chown -R www-data.root /etc/horde >> /dev/null 2>&1");
 system("chown -R www-data.root /usr/share/horde >> /dev/null 2>&1");
 system("chmod -R 555 /usr/share/horde/imp/lib/*.lib >> /dev/null 2>&1");
 system("chmod 555 /etc/horde/imp/* >> /dev/null 2>&1");
 system("chmod -R o-rwx /etc/horde/imp >> /dev/null 2>&1");
 system("chmod -R 555 /usr/share/horde/lib/*.lib >> /dev/null 2>&1");

     print "\n\nIMP is already configured; I\'ll leave\n";
     print "the existing configuration untouched in a .bak \n";
     print "Use /usr/sbin/impconfig to reconfigure it.\n\n";


if ($restart_apache)
{
  if (-s "/usr/sbin/apache-ssl") {
    print "\nRestarting Apache-SSL...\n";
    system("/etc/init.d/apache-ssl restart >> /dev/null 2>&1")
  } else {
    print "\nRestarting Apache...\n";
    system("/etc/init.d/apache restart >> /dev/null 2>&1")
  }
}  

        exit(0);
}



    undef @files;

		$configtype='1';
    if (-s "/usr/bin/psql") {
                $dbtype='pgsql';
		$impmgr="www-data";
	 	$impmgr_passwd='';
		$configtype='3';
    } else {
      if (-s "/usr/bin/mysql") {
                $dbtype="mysql";
		$impmgr='impmgr';
		$impmgr_passwd='impmgr';
		$configtype='2';
      }
    }

sub buildconf() {


    if (-s "/usr/bin/psql") {
                $dbtype='pgsql';
                $impmgr="www-data";
                $impmgr_passwd='';
                $configtype='3';
    } else {
      if (-s "/usr/bin/mysql") {
                $dbtype="mysql";
                $impmgr='impmgr';
                $impmgr_passwd='impmgr';
                $configtype='2';
      }
    }


    &setfile('defaults.php3',
'<?php',
"

/* the session file (dbm file) */
\$default->session_file = './lib/sessions';

/* Email address to send problem reports */
\$default->problem_email             = 'root\@localhost';
\$default->problem_reporting         = true;

/* For debugging purposes */
\$default->error_level               = 15;

/* The longest that things like file uploads and slow functions should be
 * allowed to run. 0 means run until termination (forever if infinite loop).
 * NOTE: you can't set this to 0 if safe_mode is on. */
\$default->max_execution_time        = 0;

/* Server Specific Configuration */
\$default->localhost                 = '$syshostname';

/* Imap Server Default */
\$default->server                    = '$syshostname';
\$default->from_server               = '$syshostname';
\$default->port                      = 143;

/* Web server configuration */
\$default->root_url                  = '/imp';
\$default->include_dir               = './templates';
\$default->graphics_url              = \$default->root_url . '/graphics';

/* Folder configuration */
\$default->folders                   = '';
\$default->use_imap_subscribe        = true;
\$default->show_dotfiles             = false;
\$default->sent_mail                 = 'sent-mail';
\$default->save_sent_mail            = true;
\$default->postponed                 = 'postponed-msgs';

/* Allow caching of the pages */
\$default->cache_pages               = false;

/* Ldap searching */
\$default->use_ldap_search           = false;

/* user is presented with an list of available imap servers */
\$default->use_server_list           = false;

/* User changable items */
\$default->user_change_server        = true;
\$default->user_change_folder        = true;
\$default->user_change_from          = true;
\$default->user_change_fullname      = true;
\$default->user_use_addressbook      = true;

/* New mail configuration */
/* Refresh between check for new mail */
\$default->refresh_delay                  = 300;
\$default->newmail_popup                  = true;

/* Cookie configuration */
\$default->session_enabled           = false;
\$default->session_timeout           = 300;
\$default->cookie_timeout            = 10000;

/* Path to sendmail */
\$default->path_to_sendmail          = '/usr/sbin/sendmail';

/* Ispell setup */
\$default->path_to_ispell            = '/usr/bin/ispell';

/* Mswordview setup */
\$default->path_to_mswordview        = '/usr/bin/mswordview -n';

/* path to tar so that tarballs can be listed */
\$default->path_to_tar               = '/bin/tar';

/* SSL Configuration block */
\$default->secure                    = true;

/* Cyrus configuration block */
\$default->personal_folders          = '';
// cyrus configs may look like this:
// \$default->personal_folders       = 'INBOX.';

/* Default Language */
\$default->language                  = 'en';
\$default->user_change_language      = true;

\$default->append_header             = true;
\$default->append_trailer            = true;

\$default->text_parts_inline         = true;

/* database config */
\$default->use_db                    = true;
\$default->db_user_name              = '$impmgr';
\$default->db_password               = '$impmgr_passwd';
\$default->db_name                   = 'imp';
\$default->db_server_name            = 'localhost';
\$default->db_pref_table             = 'imp_pref';
\$default->db_address_table          = 'imp_addr';
\$default->db_connect_string         = '';
\$default->db_server_port            = '';
\$default->db_server_options         = '';
\$default->db_server_tty             = '';

/* IMP Account Signup */
\$default->signup_email              = 'root\@localhost';
\$default->signup                    = false;

?>
");     



sub setfileshort {
    local ($filename,$value) = @_;
    push(@files,$filename);
    $filecontents{$filename}= $value;
}

sub setfile {
    local ($filename,$value1,$value2,$d) = @_;
    chop($d=`date`);
    $v=
"$value1\
$value2";
    push(@files,$filename);
    $filecontents{$filename}=$v;
}

sub reswarn {
    print STDERR "$_[0]\n";
    return 0;
}

for $f (@files) {
    open(N,">$etc/$f.postinstnew") || die "Error creating $etc/$f.postinstnew: $!\n";
    print(N $filecontents{$f}) || die "Error writing $etc/$f.postinstnew: $!\n";
    close(N) || die "Error closing $etc/$f.postinstnew: $!\n";
}

while (defined($f= pop(@files))) {
    rename("$etc/$f.postinstnew","$etc/$f") || die "Error installing $etc/$f: $!\n";
}


while (defined($f= pop(@files))) {
    rename("$etc/$f.postinstnew","$etc/$f") || die "Error installing $etc/$f: $!\n";
}


}

sub query {
    local ($question, $varname, $default, $check, $opts) = @_;
    local ($allowempty, $response, $e);
    print "\n";
    $allowempty= $opts =~ m/e/;
    if (eval "defined(\$$varname)") {
        $default= eval "\$$varname";
        $default='none' if $default eq '' && $allowempty;
    }
    for (;;) {
        print "$question\nEnter value (";
        print "default=\`$default', " if length($default);
        print "\`x' to restart): ";
	$!=0; defined($iread=<STDIN>) || die "impconfig: EOF/error on stdin: $!\n";
        $_= $iread; s/^\s+//; s/\s+$//;
        return 0 if m/^x$/i;
        $_= $default if $_ eq '';
        if (!length($_)) {
            print "  Sorry, you must enter a value.\n";
            next;
        }
        $_= '' if $_ eq 'none' && $allowempty;
        $response= $_;
        last if eval $check;
        if (length($@)) {
            print STDERR "  Aargh, bug - bug - please report:\n$@\nin\n $check\n";
            last;
        } else {
            print "  Sorry, that value is not acceptable.\n";
        }
    }
    $e= "\$$varname = \$response;";
    eval $e; length($@) && die "aargh - internal error ($e): $@";
    1;
}


### Configure IMP Libraries ###

 system("cd /usr/share/horde/imp/lib/src && ./build.pl --with-config=/etc/horde/imp/build.opts >> /dev/null 2>&1");

 buildconf();

### Restart Database ###

if ($configtype == 3) {
  print "\nSeeing if the Database needs to be configured...\n";
  $db_owner = "postgres";
  $com1 = "/usr/bin/psql -d horde -c '\\dt'";
  $com2 = "su - ";
  $com4 = ' -c "';
  $com3 = '" | grep horde_pref';
  if (system("$com2$db_owner$com4$com1$com3 >/dev/null"))
  {
    print "Attempting to auto-config PostgreSQL for you...\n";
    system("su - postgres -c '/usr/share/doc/imp/scripts/pgsql_cuser.sh'");
    system("su - postgres -c '/usr/bin/psql template1 < /usr/share/doc/imp/scripts/pgsql_create.sql'");
  } else {
    print "Postgres seems to be already configured\n";
  }

  print "
Restarting PostgreSql";
  system("/etc/init.d/postgresql restart >> /dev/null 2>&1 ");
}

if ($configtype == 2) {
 print "Attempting to auto-config MySQL for you...
This may not work if you have actually set a password for your
mysql system.\n";
 system("/usr/bin/mysql < /usr/share/doc/imp/scripts/mysql_create.sql ");
  print "
Restarting MySql";
  system("/etc/init.d/mysql restart >> /dev/null 2>&1 ");
}


### Change file permissions for security ###

  system("chown -R www-data.root /etc/horde >> /dev/null 2>&1");
  system("chown -R www-data.root /usr/share/horde >> /dev/null 2>&1");
  system("chmod -R 555 /usr/share/horde/imp/lib/*.lib >> /dev/null 2>&1");
  system("chmod 555 /etc/horde/imp/* >> /dev/null 2>&1");
  system("chmod -R o-rwx /etc/horde/imp >> /dev/null 2>&1");
  system("chmod -R 555 /usr/share/horde/lib/*.lib >> /dev/null 2>&1");

###  Restart the web server ###

 if (-s "/usr/sbin/apache-ssl") {
   print "
Restarting Apache-SSL";
   system("/etc/init.d/apache-ssl restart");

 } else {
    if (-s "/usr/sbin/apache") {
   print "
Restarting Apache";
   system("/etc/init.d/apache restart >> /dev/null 2>&1");

    } else {
   print "
Please restart your web server";
    }
 }

### Extra Information ###
print "

You can now customize IMP by running /usr/sbin/impconfig or
manually editing /etc/horde/imp/defaults.php3.  

You can also use the new setup.php3 web based configuration by
going into /usr/share/horde and running ./install.sh then
point your browser to http://localhost/horde/setup.php3

afterwards you need to run the secure.sh script

You can now point your browser to:

         http://$syshostname/horde

";

system("sleep 5");

### Done ###
