#! @PERL@ -w
#-*- perl -*-
#
#  Copyright (C) 2003 Ken'ichi Fukamachi
#   All rights reserved. This program is free software; you can
#   redistribute it and/or modify it under the same terms as Perl itself.
#
# $FML: install.pl.in,v 1.6 2004/07/27 15:48:09 fukachan Exp $
#

use strict;
use Carp;
use lib qw(fml/lib cpan/lib img/lib);
use vars qw($install_root);

# Run this from the top-level fml source directory.
$ENV{'PATH'} = '/usr/xpg4/bin:/bin:/usr/bin:/usr/sbin:/usr/etc:/sbin:/etc';

my $debug = 0;

if ($0 eq __FILE__) {
    umask(022);

    unless (@ARGV) {
	croak("Usage: $0 install.cf\n");
    }
    else {
	_init();
	_install( $ARGV[0] );
    }
}
else {
    croak("Usage: $0 install.cf\n");
}

exit 0;


# Descriptions: initialize some variables.
#    Arguments: none
# Side Effects: set $install_root
# Return Value: none
sub _init
{
    # inherit enviromental variable
    $install_root = $ENV{ 'install_root' } || '';
}


# Descriptions: install fml8
#    Arguments: STR($cf)
# Side Effects: install a lot of files: bin, lib, libexec/ and share/.
# Return Value: none
sub _install
{
    my ($cf) = @_;
    my $format    = "%20s = %s\n";

    use FML::Install;
    my $installer = new FML::Install;
    my $config    = $installer->load_install_cf( $cf );

    # change install_root if needed.
    if ($install_root) {
	$installer->set_install_root($install_root);
    }

    printf $format, "version", $installer->get_version() if $debug;

    $installer->is_valid_owner( $config->{ owner } );
    $installer->is_valid_group( $config->{ group } );

    if ($installer->is_run_as_root()) {

	my $list = $config->get_as_array_ref('mandatory_dirs');
	for my $dir (@$list) {
	    my $path = $installer->path($dir);
	    if ($install_root) {
		$path = File::Spec->catfile($install_root, $path);
	    }

	    printf $format, $dir, $path if $debug;
	    unless (-d $path) {
		$installer->mkdir($path);
	    }
	    else {
		print STDERR "ok $path\n" if $debug;
	    }
	}

	$installer->install_main_cf();
	$installer->install_sample_cf_files();
	$installer->install_default_config_files();
	$installer->install_mtree_dir();
	$installer->install_compat_dir();
	$installer->install_lib_dir();
	$installer->install_libexec_dir();
	$installer->install_data_dir();

	# install programs hereafter.
	$installer->install_bin_programs();

	# update loader.
	if ( $installer->need_resymlink_loader() ) {
	    $installer->install_loader();
	    $installer->resymlink_loader();
	}

	# set up ml_spool_dir such as /var/spool/ml if needed.
	$installer->setup_ml_spool_dir();
    }
    else {
	my $r = "user should be not ROOT!";
	my $s = $installer->message_nl("installer.no_root_user", $r);

	print $s if $s;
	croak("Error: run $0 as root.\n");
    }
}
