#!/usr/bin/perl -w

=head1 NAME

xt-create-config - Create a Xen configuration file for a new domain.

=cut

=head1 SYNOPSIS

  xt-create-config [options]

  Help Options:
   --help     Show this scripts help information.
   --manual   Read this scripts manual.
   --version  Show the version number and exit.

  Debugging Options:
   --verbose  Be verbose in our execution.

  Mandatory Options:
   --output   The directory to save our configuration file to.

  All other options from xen-create-image, such as the new IP address(es)
 to give to the new instance, will be passed as environmental variables.

=cut

=head1 ABOUT

  This script is invoked by B<xen-create-image> after it has created and
 customised a new Xen domain.  It is responsible for creating the
 configuration file that Xen should use to start the instance.

  The configuration file will be created in the directory /etc/xen using
 the template file B</etc/xen-tools/xm.tmpl> to specify what is included.

  If you wish to make changes to the Xen configuration file for every
 domain which is created then you should modify the master template rather
 than fixing up each new instances configuration afterwards.

=cut


=head1 ARGUMENT PASSING

  This script will be invoked with a full copy of the arguments from
 xen-create-image in its environment, along with several command line
 arguments.

=cut


=head1 AUTHOR

 Steve
 --
 http://www.steve.org.uk/

 $Id: xt-create-xen-config,v 1.15 2006/08/16 09:42:44 steve Exp $

=cut


=head1 LICENSE

Copyright (c) 2005-2006 by Steve Kemp.  All rights reserved.

This module is free software;
you can redistribute it and/or modify it under
the same terms as Perl itself.
The LICENSE file contains the full text of the license.

=cut


use strict;
use Env;
use Getopt::Long;
use Pod::Usage;
use Text::Template;



#
#  Configuration values read from the command line.
#
#  We do not need to read any configuration file.
#
my %CONFIG;

#
#  Default options
#
$CONFIG{'template'} = '/etc/xen-tools/xm.tmpl';


#
# Release number.
#
my $RELEASE = '2.3';




#
#  Parse the command line arguments.
#
parseCommandLineArguments();


#
#  Check our arguments.
#
checkArguments();


#
#  Create the Xen configuration file.
#
createXenConfig();


#
#  Exit cleanly - any errors which have already occurred will result
# in "exit 1".
#
exit 0;






=begin doc

  Parse the command line arguments this script was given.

=end doc

=cut

sub parseCommandLineArguments
{
    my $HELP    = 0;
    my $MANUAL  = 0;
    my $VERSION = 0;

    #
    #  Parse options.
    #
    GetOptions(
              "output=s",   \$CONFIG{'output'},
              "template=s", \$CONFIG{'template'},
              "verbose",    \$CONFIG{'verbose'},
              "help",       \$HELP,
              "manual",     \$MANUAL,
              "version",    \$VERSION
             );

    pod2usage(1) if $HELP;
    pod2usage(-verbose => 2 ) if $MANUAL;


    if ( $VERSION )
    {
       my $REVISION      = '$Revision: 1.15 $';

       if ( $REVISION =~ /1.([0-9.]+) / )
       {
           $REVISION = $1;
       }

       print "xt-create-xen-config release $RELEASE - CVS: $REVISION\n";
       exit;

    }
}



=begin doc

  Test that the command line arguments we were given make sense.

=end doc

=cut

sub checkArguments
{
    #
    #  We require an output location.
    #
    if ( ! defined( $CONFIG{'output'} ) )
    {
       print "The '--output' argument is mandatory\n";
       exit 1;
    }

    #
    #  The output location should be a directory which exists.
    #
    if ( ! -d $CONFIG{'output'} )
    {
        print "The output directory we've been given, $CONFIG{'output'}, doesnt exist\n";
        print "Aborting\n";
        exit 1;
    }


    #
    #  Make sure that any specified template file exists.
    #
    if ( defined( $CONFIG{'template'} ) )
    {
        if ( ! -e $CONFIG{'template'} )
        {
            print "The specified template file, $CONFIG{'template'} does not exist.\n";
            exit 1;
        }
    }
    else
    {
        print "A template file was not specified.  Aborting\n";
        exit 1;
    }
}



=begin doc

  This function does the real work of creating the Xen configuration
 file.  We modify some of the variables contained in our environment
 and then process the template file with B<Text::Template>.

=end doc

=cut

sub createXenConfig
{
    #
    #  The output file we're going to process.
    #
    my $file = $CONFIG{'output'} . '/' . $ENV{'hostname'} . '.cfg';

    #
    #  The template we're going to read from.
    #
    my $template = new Text::Template( TYPE => 'FILE',
                                       SOURCE => $CONFIG{'template'} );


    #
    #  The device we're using.
    #
    my $device = 'sda';
    if ( defined( $ENV{'ide'} ) )
    {
       $device = 'hda';
    }
    $ENV{'device'} = $device;


    #
    #  The memory size:  Strip any trailing size characters "M", "G", etc.
    #
    if ( $ENV{'memory'} =~ /([0-9]+)/ )
    {
       $ENV{'memory'} = $1;
    }


    #
    # Images as presented to Xen - either loopback images, or LVM partitions.
    #
    my $image_vbd;
    my $swap_vbd;

    if ( $ENV{'lvm'} )
    {
       $image_vbd = "phy:$ENV{'lvm'}/$ENV{'hostname'}-disk";
       $swap_vbd  = "phy:$ENV{'lvm'}/$ENV{'hostname'}-swap";
    }
    else
    {
       $image_vbd = "file:$ENV{'dir'}/domains/$ENV{'hostname'}/disk.img";
       $swap_vbd  = "file:$ENV{'dir'}/domains/$ENV{'hostname'}/swap.img";
    }
    $ENV{'image_vbd'} = $image_vbd;
    $ENV{'swap_vbd'}  = $swap_vbd;


    #
    #  Now we should have a suitable environment.  What we want to
    # do now is to make sure that these environmental variables are
    # made available to our template file.
    #
    my %vars;
    foreach my $key (sort keys %ENV )
    {
        $vars{$key} = $ENV{$key};
    }

    #
    #  Now output the data.
    #
    open( FILE, ">", $file );

    #
    #  The template file gets a complete copy of our configuration values.
    #
    my $result = $template->fill_in(HASH => \%vars);

    #
    #  Write the output of processing the template file, if it succeeds.
    #
    if (defined $result)
    {
        print FILE $result ;
    }
    else
    {
        print FILE "Error creating configuration file\n";
    }

    #
    #  Close the output file.
    #
    close( FILE );

}
