#!/usr/bin/perl -w
# The LearningOnline Network 
# Fedora installation script
#
# $Id: install.pl,v 1.7 2005/03/24 21:42:46 matthew Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA 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; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA 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 LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# http://www.lon-capa.org/
#

use strict;
use File::Copy;
use Getopt::Long;

my $result; 
my $test;

# note: The filehandle LOG is global.
open LOG,">>loncapa_install.log" || die "Unable to open log file.\n";

print LOG '$Id: install.pl,v 1.7 2005/03/24 21:42:46 matthew Exp $'."\n";

# Some friendly subroutines
sub die_if_nonempty {
    my ($string,$error)=@_;
    return if (! defined($error));
    chomp($string);chomp($error);
    if ($string ne '') {
        print_and_log("$error\nHalting.\n");
        die;
    }
}

sub make_link_or_die {
    my ($source,$dest)=@_;
    &die_if_nonempty
        (`ln -fs $source $dest`,"Unable to link $source to $dest.");
    print LOG "Link from $source to $dest made successfully\n";
}

sub writelog {
    while ($_ = shift) {
        chomp;
        print LOG "$_\n";
    }
}

sub print_and_log {
    while ($_=shift) {
        chomp;
        print "$_\n";
        print LOG "$_\n";
    }
}

###############################
#                             #
#  Define default behaviour   #
#                             #
###############################
my $make_www       = 1;
my $install_pwauth = 1;
my $setup_mysql    = 1;
my $setup_mysql_permissions = 1;
my $stop_services     = 0;
my $install_httpd_conf = 1;
my $download_loncapa  = 1;
my $showhelp          = 0;

###################################
#
#  Deal with command line options
#
###################################
GetOptions(
	   "make_www!"                => \$make_www,
	   "install_pwauth!"          => \$install_pwauth,
	   "setup_mysql!"             => \$setup_mysql,
	   "setup_mysql_permissions!" => \$setup_mysql_permissions,
	   "stop_services!"           => \$stop_services,
	   "install_httpd_conf!"      => \$install_httpd_conf,
	   "download_loncapa!"        => \$download_loncapa,
           "help"                     => \$showhelp,
	   );

if ($showhelp) {
    print <<END;
$0: The following options are available:

  Option               Default  Description
---------------------------------------------
make_www                 yes    Create the www user
install_pwauth           yes    Install pwauth
setup_mysql              yes    Configure MySQL
setup_mysql_permissions  yes    Configure MySQL Permissions
stop_services            no     Stop unneeded services
install_httpd_conf       yes    Install LON-CAPA provided httpd.conf
download_loncapa         yes    Download LON-CAPA sources code
help                            Show this help

Examples:

Default behaviour is the same as:

  $0 --make_www --install_pwauth --setup_mysql \
     --setup_mysql_permissions --install_httpd_conf \
     --download_loncapa 

Do everything as normal but do not configure MySQL database:

  $0 --nosetup_mysql

END
    exit;
}

print <<"END";
********************************************************************

                    Welcome to LON-CAPA 

This script will configure the base software that LON-CAPA needs to
run properly. 

********************************************************************
END

my $instdir = `pwd`;
chomp($instdir);

if ($make_www) {
    &setup_www();
} else {
    &print_and_log("Skipping creation of user 'www'.\n");
}

if ($install_pwauth) {
    &build_and_install_mod_auth_external();
} else {
    &print_and_log("Skipping pwauth installation.\n");
}

if ($stop_services) {
    &kill_extra_services();
} else {
    # No message as not stopping the services is the default
}

if ($setup_mysql) {
    &setup_mysql();
} else {
    &print_and_log("Skipping configuration of MySQL.\n");
}

##
## Set up httpd 
##
print_and_log("Setting httpd to start on boot up.\n");
system("/sbin/chkconfig httpd on");

if ($install_httpd_conf) {
    &copy_httpd_conf();
}

#my $lctarball = 'loncapa-current.tar.gz';
my $lctarball = 'loncapa-fedora-current.tar.gz';
if ($download_loncapa) {
    &download_loncapa($lctarball);
} else {
    print_and_log(<<"END");

You have requested not to have the LON-CAPA source downloaded from 
install.loncapa.org.

LON-CAPA is not yet installed on your system.

You may retrieve the source for LON-CAPA by executing :
wget http://install.loncapa.org/versions/$lctarball
END
}

exit;

####################################################################
####################################################################

###############################################
###############################################
sub setup_www {
    ##
    ## Set up www
    ##
    print_and_log("Creating user 'www'\n");
    $result = `/usr/sbin/useradd www`;
    if (! (($result eq '') || ($result =~ /user www exists/))) {
	die "Unable to add user www.  Halting.\n";
    }
    writelog ($result);
}

###############################################
###############################################
sub uid_of_www {
    my ($num) = (getpwnam('www'))[2];
    return $num;
}

###############################################
##
## mod_auth_external
##
###############################################
sub build_and_install_mod_auth_external {
    my $num = &uid_of_www();
    # Patch mod_auth_external
    print_and_log("Building authentication system for LON-CAPA users.\n");
    my $patch = <<"ENDPATCH";
148c148
< #define SERVER_UIDS 99		/* user "nobody" */
---
> #define SERVER_UIDS $num		/* user "www" */
ENDPATCH

    if (! -e "/usr/bin/patch") {
	print_and_log("You must install the software development tools package ".
		      "when installing RedHat.\n");
	die;
    }
    &die_if_nonempty(`cd /tmp; tar zxf $instdir/mod_auth_external-2.1.13.tar.gz`,
		     "Unable to extract mod_auth_external\n");
    my $dir = "/tmp/mod_auth_external-2.1.13/pwauth";
    open PATCH, "| patch $dir/config.h" || 
	die "Unable to start patch for mod_auth_external.  Halting\n";
    print PATCH $patch;
    close PATCH;
    print_and_log("\n");
    ##
    ## Compile patched pwauth
    ##
    print_and_log("Compiling pwauth\n");
    $result = `cd $dir/; make`;
    my $expected = <<"END";
gcc -g    -c -o pwauth.o pwauth.c
gcc -o pwauth -g  pwauth.o -lcrypt
END
    if ($result ne $expected) {
	die "Unable to compile patched pwauth.  Halting.\n";
    }    
    print_and_log( "appearant success compiling pwauth:\n".$result );
    # Install patched pwauth
    print_and_log("Copying pwauth to /usr/local/sbin\n");
    if (! copy "$dir/pwauth","/usr/local/sbin/pwauth") {
	die "Unable to copy $dir/pwauth to /usr/local/sbin/pwauth.\n$!\nHalting\n";
    }
    if (! chmod (06755, "/usr/local/sbin/pwauth")) {
	die "Unable to set permissions on /usr/local/sbin/pwauth.\n";
    }
    print_and_log("\n");
}

###############################################
##
## Kill some services
##
###############################################
sub kill_extra_services {
    &print_and_log("\nKilling unneccessary services.\n");
    foreach my $service ('cups','sendmail') {
	&print_and_log(`/etc/init.d/$service stop`);
	&print_and_log("removing $service from startup.\n");
	&print_and_log(`chkconfig --del $service`);
    }
}

###############################################
##
## Set up mysql
##
###############################################
sub setup_mysql {
    print_and_log("Setting mysqld to start on boot up.\n");
    system("/sbin/chkconfig --add mysqld");
    system("/sbin/chkconfig mysqld on");
    &writelog(`/sbin/chkconfig --list mysqld`);
    #
    writelog("mysql will start automatically on boot.\n");
    writelog(`/etc/rc.d/init.d/mysqld start`);
    print_and_log("Waiting for mysql daemon to start.\n");
    sleep 5;
    my $status = system("/etc/rc.d/init.d/mysqld status");
    if ($status != 0) {
	die "Unable to start mysql daemon\nHalting\n";
    } else {
	print_and_log("Mysql daemon is running.\n");
    }
    print_and_log("\n");
    #
    my $mysql_commands = "CREATE DATABASE loncapa;\n";
    if ($setup_mysql_permissions) {
	##
	## Get root password for mysql client
	##
	print <<END;
Please enter a root password for the mysql database.
It does not have to match your root account password, but you will need
to remember it.
END
        my $rootpass = <>;
	chomp $rootpass;
	$mysql_commands .= <<"END";
INSERT INTO user (Host, User, Password)
VALUES ('localhost','www',password('localhostkey'));
INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Grant_priv,References_priv,Index_priv,Alter_priv) VALUES ('localhost','loncapa','www','Y','Y','Y','Y','Y','Y','N','Y','Y','Y');
SET PASSWORD FOR root\@localhost=PASSWORD('$rootpass');
DELETE FROM user WHERE host<>'localhost';
FLUSH PRIVILEGES;
END
        print_and_log("Retrieved MySQL root password.\n");
    } else {
	print_and_log("Skipping mysql permissions setup.\n");
    }
    $mysql_commands .= <<"ENDMYSQL";
USE loncapa;
CREATE TABLE IF NOT EXISTS metadata (title TEXT, author TEXT, subject TEXT, url TEXT, keywords TEXT, version TEXT, notes TEXT, abstract TEXT, mime TEXT, language TEXT, creationdate DATETIME, lastrevisiondate DATETIME, owner TEXT, copyright TEXT, FULLTEXT idx_title (title), FULLTEXT idx_author (author), FULLTEXT idx_subject (subject), FULLTEXT idx_url (url), FULLTEXT idx_keywords (keywords), FULLTEXT idx_version (version), FULLTEXT idx_notes (notes), FULLTEXT idx_abstract (abstract), FULLTEXT idx_mime (mime), FULLTEXT idx_language (language), FULLTEXT idx_owner (owner), FULLTEXT idx_copyright (copyright)) TYPE=MYISAM;
EXIT
ENDMYSQL
    ##
    ## Execute the MySQL commands
    ##
    print_and_log("Starting mysql client.\n");
    open MYSQL, "|mysql -u root mysql" || die "Unable to start mysql\n";
    print MYSQL $mysql_commands;

    close MYSQL;
    print_and_log("\n");
}


###############################################
##
## Copy our (probably lousy) httpd.conf to its rightful place
##
###############################################
sub copy_httpd_conf {
    print_and_log("Copying our httpd.conf to /etc/httpd/conf/httpd.conf\n");
    copy "/etc/httpd/conf/httpd.conf","/etc/httpd/conf/httpd.conf.original";
    copy "$instdir/httpd.conf","/etc/httpd/conf/httpd.conf";
    chmod 0444,"/etc/httpd/conf/httpd.conf";
    print_and_log("\n");
}


###############################################
##
## Retrieve the latest LON-CAPA release
##
###############################################
sub download_loncapa {
    my ($lctarball) = @_;
    if (! -e "$instdir/$lctarball") {
	print_and_log("Retrieving LON-CAPA source files from ".
		      "http://install.loncapa.org\n");
	system("wget http://install.loncapa.org/versions/$lctarball ".
	       "2>/dev/null 1>/dev/null");
	if (! -e "./$lctarball") {
	    die("Unable to retrieve LON-CAPA source files from\n".
		"http://install.loncapa.org/versions/$lctarball\n");
	}
	print_and_log("\n");
    } else {
	print_and_log(<<"END");
------------------------------------------------------------------------

You seem to have a version of loncapa-current.tar.gz in $instdir.  
This copy will be used and a new version will NOT be downloaded.  
If you wish, you may download a new version by executing:

wget http://install.loncapa.org/versions/loncapa-fedora-current.tar.gz

------------------------------------------------------------------------
END
    }

    ##
    ## untar loncapa.tar.gz
    ##
    print_and_log("Extracting LON-CAPA source files\n");
    writelog(`cd ~root; tar zxf $instdir/$lctarball`);
    print_and_log("\n");
    print <<"ENDMSG";
All of the extra files seem to have been installed correctly.  It remains for 
you to execute the following commands:

cd /root/loncapa-N.N     (N.N should correspond to a version number like '0.4')
./UPDATE

If you have any trouble, please see http://install.loncapa.org/ and 
http://help.loncapa.org/.  
ENDMSG
}

close LOG;

