#!/usr/bin/perl -w
#
#  This script copies "essential" files from the host to the new
# system.
#
#  At the same time it tries to copy all non-system accounts from
# the host system into the new guest unless the root password is
# being setup with --passwd.
#
# Steve
# --
# http://www.steve.org.uk/


use strict;
use Env;
use File::Copy;


my $prefix = shift;

die "Prefix must be given"  unless defined( $prefix );
die "Prefix must be a directory" unless ( -d $prefix );


#
#  Make sure we have $prefix/etc
#
die "Prefix is missing /etc : $prefix" unless ( -d $prefix . "/etc" );


#
#  Copy some files literally.
#
my @files = (
              "/etc/resolv.conf",
            );

foreach my $file ( @files )
{
    $ENV{'verbose'} && print "Copying from host -> guest: $file\n";
    File::Copy::copy( $file, $prefix . "/etc/" );
}


#
#  If the user is specifying the --passwd flag then don't do anything else.
#
if ( $ENV{'passwd'} )
{
    exit 0;
}


#
#  Otherwise we want to copy all non-system accounts from the files:
#
#     /etc/passwd + /etc/shadow
#
open( ORIG, "<", "/etc/passwd" )
  or die "Failed to open /etc/passwd - $!";
open( NEW,  ">>", $prefix . "/etc/passwd" )
  or die "Failed to open $prefix/etc/passwd - $!";

#
#  Here we store the user accounts we've copied over so that we
# can copy the shadow lines too.
#
my %copied;

#
#  Read the lines from the /etc/passwd on the host.
#
foreach my $line ( <ORIG> )
{
    chomp( $line );

    #
    #  Split up line.
    #
    if ( $line =~ /^([^:]+):([^:]+):([^:]+)/ )
    {
        my $user = $1;
        my $pass = $2;
        my $uid  = $3;

        #
        #  A non-system account.
        #
        if ( ( $uid >= 1000 ) &&
             ( $user ne "nobody" ) )
        {
            $ENV{'verbose'} && print "Adding '$user' to /etc/passwd on guest\n";
            print NEW $line . "\n";

            #
            # Save the username we copied, so we can append the /etc/shadow
            # lines too.
            #
            $copied{ $user } = 1;
        }
    }
}
close( NEW );
close( ORIG );


#
#  Patchup /etc/shadow on the new image, to ensure that it has the
# lines for each user we copied.
#
foreach my $username ( keys %copied )
{
    #
    #  Open the shadow files.
    #
    open( ORIG, "<", "/etc/shadow" )
      or die "Failed to open /etc/shadow - $!";
    open( NEW,  ">>", $prefix . "/etc/shadow" )
      or die "Failed to open $prefix/etc/shadow - $!";

    #
    #  Now look for a line matching the user in the host file.
    #
    foreach my $line ( <ORIG> )
    {
        chomp( $line );
        if ( $line =~ /^$username:/ )
        {
            $ENV{'verbose'} && print "Added line to /etc/shadow for user '$username'\n";
            print NEW $line . "\n";
        }
    }

    close( ORIG );
    close( NEW );
}

