#!/usr/bin/perl -w

# $Id: genPart,v 1.7 2006/08/04 22:53:58 craig Exp $

#               Copyright (C) 2006, BroadOn Communications Corp.
#
#  These coded instructions, statements, and computer programs contain
#  unpublished  proprietary information of BroadOn Communications Corp.,
#  and  are protected by Federal copyright law. They may not be disclosed
#  to  third  parties or copied or duplicated in any form, in whole or in
#  part, without the prior written consent of BroadOn Communications Corp.


# Generate an encrypted partition given a directory that has
# processed using the genLic program.


use strict;
use Getopt::Long;
use Cwd;
use File::Basename;

my $eTicketExt       = ".eticket";
my $encryptedExt     = ".cry";

# ********************************************************************
sub
usage()
{
    print "Usage: $0 [options] <input directory>\n";
    print " Options:\n";
    print "           -h               - Print help message\n";
    print "           -k               - Keep intermediate files\n";
    print "           -o [filename]    - Name output file\n";
    print "                              default: <input dir>.prod_part\n";
}

# ********************************************************************
sub
checkedSymlink($$)
{
    my ($fileFrom, $fileTo) = @_;
    unless(symlink($fileFrom, $fileTo)) {
        print STDERR "$0: symlink of $fileFrom to $fileTo failed ($!)\n";
        return(0);
    }
}

# ********************************************************************

# Try to find the executable passed in.
# Look in '.', then /opt/broadon/pkgs/cls/bin.
# If not in either spot, just return the command name and hope
# the shell finds it.
sub findExecutable($)
{
    my ($executable) = @_;
    my ($currentDir);
    my $defaultDir = "/opt/broadon/pkgs/cls/bin";

    $currentDir = cwd();

    if (-x "$currentDir/$executable") {
        return ("$currentDir/$executable");
    }
    elsif (-x "$defaultDir/$executable") {
        return ("$defaultDir/$executable");
    }
    else {
        return ($executable);
    }
}

# ********************************************************************
# Create an encrypted partition given the component files found
# on a CLS machine.
# The encrypted data, ticket, tmd and certificates have
# already been generated
# Return the encrypted partition path name in $resultFileRef.

sub
generateEncPartition($$$$)
{
    my ($dir, $keepFiles, $resultFileRef, $verbose) = @_;
    my ($origDir, $mainDir);
    my (@allfiles);
    my ($file, $baseName, $eTicketFound, $contentFound, $tmpDirName);
    my ($eTicketName, $tmdName, $contentName, $hashName);
    my ($caName, $cpName, $xsName, @certList);
    my ($allCerts, $command);
    my $retVal = 0;


    $origDir = cwd();
    unless (chdir($dir)) {
        print "$0: Can't change to directory $dir ($!)\n";
        return(0);
    }
    $tmpDirName = "part_files.$$";
    if (-e $tmpDirName) {
        print "$0: Error - file/directory $tmpDirName exists already";
        # Don't goto exit - don't want to remove existing file/dir
        return(0);
    }

    unless (mkdir($tmpDirName)) {
        print "$0: Can't make directory $tmpDirName ($!) - exit\n";
        $retVal = 0;
        goto end;
    }

    unless (opendir(DIR_HANDLE, ".")) {
        print "Can't open directory $dir\n";
        $retVal = 0;
        goto end;
    }
    # Grab all the file names except for . and ..
    @allfiles = grep !/^\.\.?$/, readdir DIR_HANDLE;
    closedir(DIR_HANDLE);

    # Look for a file with ending $eTicketExt
    # If there isn't exactly one such file, return error.
    # Use the base name of that file to find the tmd file.
    $eTicketFound = 0;
    foreach $file (@allfiles) {
        my ($name, $suffix, $extension);

        if (-f $file && -r $file) {

            ($name, $dir, $suffix) = fileparse($file, $eTicketExt);
            if ($suffix eq $eTicketExt) {
                if ($eTicketFound == 1) {
                    print "$0: Error - more than one file with extension";
                    print " $extension was found - exit\n";
                    $retVal = 0;
                    goto end;
                }
                $eTicketFound = 1;
                $baseName = $name;
                $eTicketName = $file;
            }
        }
    }

    if ($eTicketFound == 0) {
        print "$0: Error - no file with extension";
        print " $eTicketExt was found - exit\n";
        $retVal = 0;
        goto end;
    }

    $tmdName = "$baseName.tmd";
    if (! -r $tmdName) {
        print "$0: Error - can't read TMD file $baseName.tmd - exit";
        $retVal = 0;
        goto end;
    }

    $contentFound = 0;
    foreach $file (@allfiles) {
        my ($name, $suffix, $extension);

        if (-f $file && -r $file) {

            ($name, $dir, $suffix) = fileparse($file, $encryptedExt);
            if ($suffix eq $encryptedExt) {
                if ($contentFound == 1) {
                    print "$0: Error - more than one file with extension";
                    print " $encryptedExt was found - exit\n";
                    $retVal = 0;
                    goto end;
                }
                $contentFound = 1;
                $contentName = $file;
            }
        }
    }

    if ($contentFound == 0) {
        print "$0: Error - no file with extension";
        print " $encryptedExt was found - exit\n";
        goto end;
    }

    $hashName = "h3Hashes";
    if (! -r $hashName) {
        print "$0: Error - can't read hash file $hashName\n";
        goto end;
    }

    $mainDir = cwd();
    unless (chdir($tmpDirName)) {
        print "$0: Can't change to directory $tmpDirName ($!)\n";
        goto end;
    }

    unless (checkedSymlink("../$eTicketName", "$baseName.tik")) {
        goto end;
    }
    unless (checkedSymlink("../$tmdName", "$baseName.tmd")) {
        goto end;
    }
    unless (checkedSymlink("../$contentName", "$baseName.app")) {
        goto end;
    }
    unless (checkedSymlink("../$hashName", "$baseName.hash")) {
        goto end;
    }

    unless (chdir($mainDir)) {
        print "$0: Can't change to directory $mainDir ($!)\n";
        goto end;
    }

    $caName = "CA-cert.raw";
    $cpName = "CP-cert.raw";
    $xsName = "XS-cert.raw";

    @certList = ($caName, $cpName, $xsName);

    foreach $file (@certList) {
        if (! -r $file) {
            print "$0: File $file doesn't exist or isn't readable - exit\n";
            goto end;
        }
    }

    $allCerts = "$tmpDirName/allCerts";

    $command = "cat $caName $cpName $xsName > $allCerts"; 
    if (system($command) != 0) {
        print "$0: Command $command failed - exit\n";
        goto end;
    }

    my $partitionPath = findExecutable("rvl_prod_partition");

    my $resultName = "$baseName.prod_part";
    $command = "$partitionPath -c $tmpDirName -x $allCerts -o $resultName"; 
    if ($keepFiles) {
        $command .= " -k";
    }
    if (system($command) != 0) {
        print "$0: Assembling the partition failed.\n";
        print "$0: Command was: $command\n";
        goto end;
    }
    $$resultFileRef = cwd() .  "/$resultName";
    $retVal = 1;

end:
    if (! $keepFiles && -e $tmpDirName) {
        if (system("rm -r $tmpDirName") != 0) {
            print "$0: Can't remove temporary directory $tmpDirName\n";
        }
    }
    unless (chdir($origDir)) {
        print "Can't change to directory $origDir\n";
        return;
    }
    return($retVal);
}

# *********************************************************************

sub
main()
{
    my ($help, $inputDir,  $keep, $outputName, $verbose);
    my ($optReturn, $resultPath, $command);
    my ($name, $dir, $suffix);
    my $exitVal = 1;

    #print "$0: arguments are: @ARGV\n";

    $optReturn = GetOptions (
                                 "help"    	        => \$help,
                                 "keep"    	        => \$keep,
                                 "output=s"    	        => \$outputName,
                                 "verbose" 	        => \$verbose,
                             );
    unless ($optReturn) {
        print STDERR "Parsing command line options failed\n";
        usage();
        exit(1);
    }
    if (defined ($help)) {
        usage();
        exit(0);
    }
    if ($#ARGV == -1) {
	print STDERR "$0: Need name of license directory\n";
	usage();
	exit(1);
    }
    elsif ($#ARGV > 0) {
	print STDERR "$0: Too many directory names\n";
	usage();
	exit(1);
    }
    else {
        $inputDir = $ARGV[0];
    }

    unless (defined ($verbose)) {
        $verbose = 0;
    }


    unless (generateEncPartition($inputDir, $keep, \$resultPath, $verbose)) {
        print STDERR "Generating encrypted partition failed\n";
        goto end;
    }

    unless (defined($outputName)) {
        my ($baseName, @pathList);
        @pathList = split (/\//, $inputDir);
        if ($#pathList == 0) {
            $baseName = $pathList[0];
        }
        else {
            my ($fullName);

            if ($pathList[$#pathList] =~ m/v[\d]+/) {
                $fullName = $pathList[$#pathList - 1];
            }
            else {
                $fullName = $pathList[$#pathList];
            }
            $suffix = rindex($fullName, ".");
            if ($suffix == -1) {
                $baseName = $fullName;
            }
            else {
                $baseName = substr($fullName, 0, $suffix);
            }
        }
        $outputName = "$baseName.prod_part";
    }
    unless (rename ($resultPath, $outputName)) {
        print STDERR "$0: Unable to rename encrypted partition to $outputName ($!)\n";
        goto end;
    }
    $exitVal = 0;

end:
    exit($exitVal);
}

main;
