#!/usr/bin/perl -w
###################################################################
#
#       (c) Copyright GlobespanVirata 2002, 2003
#
# mkinitrd : build an initrd image from a template directory 
# structure.
#
use strict;
use File::Find;
use File::Basename;
use vars qw($opt_h $opt_v $opt_t $opt_s);
use Getopt::Std;

my $MKINITRD_VERSION = "1.00";

getopts('hvt:s:');

usage() if ( $opt_h );


# This is not an argument to an option, so will not be eaten byt getopts
my $product = shift;

usage() if  ( !defined( $product ) );

# Grab some environment set by the build scripts
my $pwd = $ENV{"PWD"};
my $hwtype = $ENV{"HWTYPE_PREFIX"};
my $debug = $ENV{"DEBUG_DIR"};

# We need a scratch file from which to make symlinks
my $workfile = $pwd."/build/$hwtype$product$debug/symlink_tmp";

# Where the initrd will be made
my $DEST= $pwd."/build/$hwtype$product$debug/initrd";

# Where the files come from
my $SRC;
if ( $opt_t ) 
{
    $SRC=$opt_t;
}
else
{
    my $bin_dir = $ENV{"QUANTUM_BIN_DIR"};
    if ( defined( $bin_dir ) )
    {
        my $root;
        # Assume that the quantum modules are being put into the rd template we want
        # to use (hard to see the point otherwise). The default will be putting things
        # in /lib but this might change, so we walk back up from bin_dir until we find
        # something that looks like a root.
        while( ( is_plausible_root( $bin_dir ) ne "y" ) and  $bin_dir =~ /\// ) # While we haven't found a root and it could still exist
        {
            $bin_dir =~ s/\/[^\/]*$//;   # Cut off the last dir.
        }

        $root = $bin_dir if ( is_plausible_root( $bin_dir ) eq "y"  );


        if ( defined( $root ) )
        {
            trace( "Set template root to $root based on QUANTUM_BIN_DIR\n");
            $SRC = $root;
        }
        else
        {
            die "QUANTUM_BIN_DIR is set, but mkinitrd failed to deduce the root of you template directory from it.\n";
        }
    }
    else
    {
        $SRC=$pwd."/rd_templates/default";
    }
}

# Size of FS
my $SIZE;

# Space actually used. 
my $USED = 0;

# Block size (and smallest space a file can use. */
my $BLOCKSIZE = 1024;

if ( $opt_s )
{
    $SIZE=$opt_s;
}
else
{
    $SIZE=2048;
}

# We need these two external prog.s 
my $DEBUG = find_prog("debugfs");
my $MKFS = find_prog("mke2fs");

my $NOOUTPUT = "> /dev/null 2>&1";

if ( $opt_v )
{
    print "Creating ramdisk $DEST: \n".
    "size          : $SIZE\n".
    "from files in : $SRC\n\n";
}



# Create the container file
make_imagefile();
# And make the file system in it
make_fs();

# Copy the files over...
find( \&maker, $SRC );

# Create a hard link from /bin/busybox to /sbin/init to get things started...
system( "$DEBUG -w -R 'ln /bin/busybox /sbin/init' $DEST" );

my $lfile = dirname($SRC)."/links." . basename($SRC);

if ( -f $lfile )
{
    print "Adding symlinks from $lfile...\n";
    add_symlinks( $lfile );
}

my $dfile = dirname($SRC)."/devices." . basename($SRC);

if ( -f $dfile )
{
    print "Adding device nodes from $dfile...\n";
    add_devices( $dfile );
}
else
{
    print "Couldn't find a $dfile, adding default device nodes...\n";
    # Create all the necessary devices
    make_dev( "null", "c", 1, 3 );
    make_dev( "console", "c", 5, 1 );
    make_dev( "tty0", "c", 4, 0 );
    make_dev( "ttyS0", "c", 4, 64 );
    make_dev( "ptmx", "c", 5, 2 );
    make_dev( "mtd0", "c", 90, 0 );
    make_dev( "mtd1", "c", 90, 2 );
    make_dev( "mtd2", "c", 90, 4 );
    make_dev( "mtd3", "c", 90, 6 );
    make_dev( "mtdblock0", "b", 31, 0);
    make_dev( "mtdblock1", "b", 31, 1);
    make_dev( "mtdblock2", "b", 31, 2);
    make_dev( "mtdblock3", "b", 31, 3);
    make_dev( "zero", "c", 1, 5);
}

$USED = $USED/1024;

print "*** mkinitrd done. Used $USED out of a possible $SIZE kbytes\n";

if ( $USED/$SIZE > 0.95 )
{
    print "*** WARNING: space used calculation shows ramdisk > 95% full.\n" .
          "             this is approximate, so the ramdisk may be missing files.\n".
          "             try changing the -s option to mkinitrd in your  mkproduct.pst\n";
}


################################################################################
# Utility functions

sub is_plausible_root
{
    my $dir = shift;
    my $devdir = $dir."/dev";
    my $bindir = $dir."/bin";
    my $libdir = $dir."/lib";

    return "n" unless ( $dir =~ /\// ); # The root of the host FS is NOT a plausible root


    if  ( (-d $devdir)  and (-d $libdir ) and (-d $bindir)  )
    {
        return "y";
    }
    else
    {
        return "n";
    }
}

sub trace
{
    print @_ if ( $opt_v );
}


sub usage
{
    print
    "mkinitrd v $MKINITRD_VERSION\n".
    "usage: mkinitrd [-h] [-v] [-t template_dir] [-s N] product\n".
    "      -h : print this message and exit.\n".
    "      -v : be verbose\n".
    "      -s : make disk N kB in size (default is 2048)\n".
    "      -t : use template_dir as the template for the filesystem.\n";
    exit 0;
}

sub find_prog
{
    my $tool = shift;
    my @path = split /:/, $ENV{"PATH"};
    my $res;
    my $dir;
    foreach $dir (@path)
    {
        return "$dir/$tool" if ( -x "$dir/$tool" );
    }
    # OK, it's not in their path. Check plausible places that might not be in their path...
    @path = ( "/sbin", "/usr/sbin" );
    foreach $dir (@path)
    {
        return "$dir/$tool" if ( -x "$dir/$tool" );
    }

    print "mkinitrd needs $tool, which is not in your PATH or in /sbin or in /usr/sbin. Cannot continue\n";
    exit 1;
}

# add_to_size( value )
# Add value to the total space used. Die if it exceeds the available space
#
sub add_to_size
{
    my $num = shift;
    $num = $BLOCKSIZE * int (($num + ($BLOCKSIZE -1)) / $BLOCKSIZE);
    $USED += $num;

    die "\n*** Ramdisk is full. Try increasing the -s argument to mkinitrd in your mkproduct.pst.\n" if ( $USED > $SIZE * 1024 );
    
}

# make_imagefile()
# Create a zero-filled file of size $SIZE kB called $DEST
#
sub make_imagefile
{
        my $i;
        my $n;
        my $zeros = pack "cccccccc", 0, 0, 0, 0, 0, 0, 0, 0;
        open BLANK, ">$DEST" or die "Couldn't open $DEST: $!\n";
        $n = $SIZE * 128;
        for ( $i = 0; $i < $n; $i++ )
        {
                print BLANK $zeros;
        }
        close BLANK;
}

sub make_fs
{
        open PIPE, "|$MKFS -q -b $BLOCKSIZE $DEST";
        print PIPE "y\n";
        close PIPE;
}

# make_dir( dirname )
# Make a directory in the target filesystem
#
sub make_dir
{
        my $dir = shift;
        my $targ = $dir;
        $targ =~ s/$SRC//; # Make relative to root
        my $cmd = "$DEBUG -w -R 'mkdir $targ' $DEST $NOOUTPUT";
 #       print "$cmd\n";
        system( $cmd );


        # We've presumably used one block of space. 
        add_to_size( $BLOCKSIZE );
}

# make_file( dir, file )
# Copy $SRC/dir/file to /dir/file in the target system
# 
sub make_file
{
        my $dir = shift;
        my $file = shift;
        my $targ = $dir;
        $targ =~ s/$SRC//; # Make relative to root

        open PIPE, "|$DEBUG -w $DEST $NOOUTPUT";
        print PIPE "cd $targ\n";
        print PIPE "write $dir/$file $file\n";
        print PIPE "q\n";        
        close PIPE;

        # Add file size to total
        my $size = -s "$dir/$file";

        add_to_size( $size );

}

# make_dev( name, type, major, minor )
# Make a special file called name in the /dev directory of the target
# filesystem
#
sub make_dev
{
        my $name = shift;
        my $type = shift;
        my $major = shift;
        my $minor = shift;
        my $i;

        open PIPE, "|$DEBUG -w $DEST $NOOUTPUT";
        print PIPE "cd /dev\n";
        print PIPE "mknod $name $type $major $minor\n";             
        print PIPE "mi $name\n";    # Modify inode
        if ( $type eq "c" )
        {
            print PIPE "0020600\n";         # Change perms
        }
        else
        {
            print PIPE "0060600\n";         # Change perms
        }
        for ( $i = 0; $i < 31; $i++ )
        {
                print PIPE "\n";        # Skip all the other questions...
        }
        print PIPE "q\n";        
        close PIPE;


        # We've presumably used one block of space. 
        add_to_size( $BLOCKSIZE );
}

# make_symlink( fromdir, fromfile, target )
# Make /fromdir/fromfile a symlink to target.
# This involves creating a file whose contents are the name of
# the target and then invoking modify_inode to make the 
# result a symlink.
#
sub make_symlink
{
        my $fromdir = shift;
        my $fromfile = shift;
        my $to = shift;
        my $i;

        $fromdir =~ s/$SRC//; # Make relative to root

        open TMP, ">$workfile" or die "Could not open $workfile: $!\n";
        print TMP "$to";
        close TMP;

        open PIPE, "|$DEBUG -w $DEST $NOOUTPUT";
        print PIPE "cd $fromdir\n";
        print PIPE "write $workfile $fromfile\n";
        print PIPE "mi $fromfile\n";    # Modify inode
        print PIPE "0120777\n";         # Change the mode to make it a symlink
        for ( $i = 0; $i < 31; $i++ )
        {
                print PIPE "\n";        # Skip all the other questions...
        }
        print PIPE "q\n";
        close PIPE;

        # We've presumably used one block of space. Record the fact.(OK, so if the name is really 
        # long we might use more. Ignore for now. This is all a bit approximate
        add_to_size( $BLOCKSIZE );
}

# The callback for find() : checks the type of the thing found and passes
# it to the relevant function
#
sub maker 
{
        if ( -l $_ )
        {
                my $link = $_;
                my $target = readlink $link;
#                print "symlink from $File::Find::name to $target\n";
                make_symlink( $File::Find::dir, $link, $target );
        }
        elsif ( -d $_ )
        {
#                print "new directory $File::Find::name\n";
                make_dir( $File::Find::name );
        }
        elsif ( -f $_ )
        {
                make_file( $File::Find::dir, $_ );
        }

}


# Take a file describing a load of device nodes, and create them in the FS
sub add_devices
{
    my $desc_file = shift;
    my $line;
    open LIST, "$desc_file" or die "Could not open $desc_file: $!\n";
    foreach $line (<LIST>)
    {
        chomp $line;
        next if $line =~ /^\s*\#/; # Allow comments
        next if $line =~ /^\s*$/;

        my ($name, $type, $major, $minor) = split /\s+/, $line;
        make_dev( $name, $type, $major, $minor );
    }    
}

# Take a file describing a load of symlinks, and create them in the FS
sub add_symlinks
{
    my $desc_file = shift;
    my $line;
    open LIST, "$desc_file" or die "Could not open $desc_file: $!\n";
    foreach $line (<LIST>)
    {
        chomp $line;
        next if $line =~ /^\s*\#/; # Allow comments 
        next if $line =~ /^\s*$/;
        $line =~ /(\S+)\s+(\S+)/;
        my $to = $2;
        my $from = $1;
        my $ffile = basename( $from );
        my $fdir = dirname( $from );
        make_symlink( $fdir, $ffile, $to );
    }    
}
