#!/usr/bin/perl -w

# $Id: prepPart,v 1.13 2006/10/12 19:32:32 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.


# INPUT:        a developer encrypted partition
# OUTPUT:       the decrypted files from the partition placed
#               in a directory in a form that the genLic program expects

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

my $eTicketExt       = ".eticket";
my $encryptedExt     = ".cry";
my $defaultTitleId   = "0xcafedead";
my $genLicDirExt     = ".lic";
my $genLic           = "/opt/broadon/pkgs/cls/bin/genLic";

sub
usage()
{
    print "Usage: $0 [options] <encrypted partition name>\n";
    print " Options:\n";
    print "           -f              - overwrite any existing partition components\n";
    print "           -h              - print help message\n";
    print "           -l <dir>        - Put output files in <dir>\n";
    print "                             Don't create directory structure\n";
    print "           -k              - Keep intermediate files\n";
    print "           -t <title Id>   - Give title ID [default: 0xdeadcafe]\n";
    print "                              [Only applies if license directory\n";
    print "                               is created]\n"
}

# *********************************************************************
sub
createPropertyFile($$$)
{
    my ($propertyName, $titleName, $titleId) = @_;

    unless (open (PROPERTY, ">" . $propertyName)) {
        print STDERR "$0: Can't open property file '$propertyName' for writing ($!)\n";
        return(0);
    }
    print PROPERTY "TITLE_ID = $titleId\n";
    print PROPERTY "TITLE_NAME = $titleName\n";
    print PROPERTY "TITLE_TYPE = GAME\n";
    print PROPERTY "PASSWORD = t\n";
    unless (close (PROPERTY)) {
        print STDERR "$0: Can't close property file '$propertyName' for writing ($!)\n";
        return(0);
    }
    return(1);
}
# *********************************************************************

sub 
setupLicenseDir($$$)
{
    my ($licenseDir, $titleId, $encryptDir) = @_;
    my ($origDir);
    # Directory under the license directory where the decrypted
    # files go, and where temporary files go as well.
    my $volumeName       = "v0000";

    $origDir = cwd();
    unless (mkdir ($licenseDir, 0777)) {
        print STDERR "$0: Can't make directory $licenseDir ($!)\n";
        return(0);
    }
    unless (chdir ($licenseDir)) {
        print STDERR "$0: Can't change to directory $licenseDir ($!)\n";
        return(0);
    }
    unless(createPropertyFile("properties", $licenseDir, $titleId)) {
        return(0);
    }
    unless (mkdir ($volumeName, 0777)) {
        print STDERR "$0: Can't make directory $volumeName ($!)\n";
        return(0);
    }
    $$encryptDir = cwd() . "/$volumeName";
    unless (chdir ($origDir)) {
        print STDERR "$0: Can't change to directory $origDir ($!)\n";
        return(0);
    }
    return(1);
}
# *********************************************************************

# 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);
    }
}

# *********************************************************************
# Decrypt the developer partition whose full path is '$develPartPath'.
# RETURNS: 1 if everything went OK
#          0 otherwise
# Also returns a hash in 'returnVal' with the full path to each of the
# partition components if all went well
sub
decryptPartition($$$$)
{
    my ($develPartPath, $decryptDir, $returnVal, $verbose) = @_;
    my ($command, $currentDir, $origDir, %returnVal, $key);
    my ($executablePath, $outName, $index);

    $executablePath = findExecutable("decrypt_rvl_partition");

    $origDir = cwd();

    unless (chdir ($decryptDir)) {
        print STDERR "$0: Can't change to directory $decryptDir ($!)\n";
        return(0);
    }

    $outName = "unencrypt";

    $command = "$executablePath $develPartPath -o $outName";

    if ($verbose) {
        print "Running command: '$command'\n";
    }

    if (system($command) != 0) {
        print STDERR "$0: command $command failed\n";
        return(0);
    }
    $currentDir = cwd();
    if ($verbose) {
        print ("(prepPart:decryptPartiton) currentDir = $currentDir\n");
    }

    $returnVal->{'data'}        = "$currentDir/$outName.part";
    $returnVal->{'ticket'}      = "$currentDir/$outName.ticket";
    $returnVal->{'tmd'}         = "$currentDir/$outName.tmd";
    $returnVal->{'h3Hashes'}    = "$currentDir/$outName.h3Hashes";

    foreach $key (keys %$returnVal) {
        unless (-r $returnVal->{$key}) {
            print STDERR "$0: Can't read file $returnVal->{$key}\n";
            return(0);
        }
    }
    unless (chdir ($origDir)) {
        print STDERR "$0: Can't change to directory $origDir ($!)\n";
        return(0);
    }
    return(1);
} #decryptPartition

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

# Rename a file, and check the return value.
# Print a message and return 0 if there was a problem.

sub
checkedRename($$)
{
    my ($fileFrom, $fileTo) = @_;
    unless(rename($fileFrom, $fileTo)) {
        print STDERR "$0: rename of $fileFrom to $fileTo failed ($!)\n";
        return(0);
    }
    return(1);
}
# *********************************************************************
sub setupEncryptionDir($%)
{
    my ($encryptDir, %decryptFiles) = @_;
    my ($curDir, $key);
    my %destNames = (
        data            => "000-data",
        ticket          => "eticket.template",
        tmd             => "tmd.template",
        h3Hashes        => "h3Hashes",
    );

    $curDir = cwd();
    unless (chdir($encryptDir)) {
        print STDERR "$0: Can't change to directory $encryptDir ($!)\n";
        return(0);
    }
    foreach $key (keys %decryptFiles) {
        if (-e $destNames{$key}) {
            unless (unlink($destNames{$key})) {
                print STDERR
                "$0: unlink of $encryptDir/$destNames{$key} failed\n";
                return(0);
            }
        }
        unless(checkedRename($decryptFiles{$key}, $destNames{$key})) {
            return(0);
        }
    }
    unless (chdir($curDir)) {
        print STDERR "$0: Can't change to directory $curDir ($!)\n";
        return(0);
    }
    return(1);
} # setupEncryptionDir
# *********************************************************************

sub
main()
{
    my ($help, $keep, $titleId, $verbose);
    my ($optReturn);
    my ($decryptDir, $command);
    my ($develPartName, $develPartAbsPath, %decryptFiles);
    my ($inputEncryptDir, $encryptAbsPath);
    my ($baseName, $suffix);
    my $exitVal = 1;

    $optReturn = GetOptions (
                                 "help"    	        => \$help,
                                 "keep"    	        => \$keep,
                                 "licenseDir=s"         => \$inputEncryptDir,
                                 "titleId=s"            => \$titleId,
                                 "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 developer encrypted partition\n";
	usage();
	exit(1);
    }
    elsif ($#ARGV > 0) {
	print STDERR "$0: Too many partition names\n";
	usage();
	exit(1);
    }
    else {
        $develPartName = $ARGV[0];
    }

    if (index ($develPartName, '/') == 0) {
        $develPartAbsPath = $develPartName;
    }
    else {
        $develPartAbsPath = cwd() . "/$develPartName";
    }
    #$verbose = 1;


    if (defined($titleId) && defined($inputEncryptDir)) {
        print STDERR "$0: options -l and -t are incompatible\n";
        usage();
        exit(1);
    }

    if (! defined ($keep)) {
        $keep = 0;
    }
    if (! defined ($verbose)) {
        $verbose = 0;
    }

    # Make the input encrypted directory into an absolute path
    # with no trailing '/'
    if (defined($inputEncryptDir)) {
        my $tmpStr;

        if (index ($inputEncryptDir, '/') == 0) {
            $encryptAbsPath = $inputEncryptDir;
        }
        else {
            $encryptAbsPath = cwd() . "/$inputEncryptDir";
        }
        $tmpStr = $encryptAbsPath;
        if (chop($tmpStr) eq "/") {
            $encryptAbsPath = $tmpStr;
        }
    }

    if ($verbose) {
        print "($0) input devel part is: $develPartName\n";
    }
    $suffix = rindex($develPartName, ".");
    if ($suffix == -1) {
        $baseName = $develPartName;
    }
    else {
        $baseName = substr($develPartName, 0, $suffix);
    }
    #print "Base name is: $develPart\n";

    # If the user specified a destination directory, do the decryption
    # there in case the file system in the current working directory
    # is too small
    if (defined($encryptAbsPath)) {
        $decryptDir = "$encryptAbsPath/.decryptDir_$$";
    }
    else {
        $decryptDir = ".decryptDir_$$";
    }

    if (-d $decryptDir) {
        if (system("rm -r $decryptDir") != 0) {
            print STDERR "$0: Can't remove $decryptDir - exit\n";
            goto end;
        }
    }
    unless (mkdir ($decryptDir, 0777)) {
        print STDERR "$0: Can't make directory $decryptDir ($!) -exit\n";
        goto end;
    }

    if ($verbose) {
        print "$0: Decrypting into directory '$decryptDir'\n";
    }

    unless(decryptPartition($develPartAbsPath, $decryptDir,
                            \%decryptFiles, $verbose)) {
        print STDERR "$0: Decrypting files failed -exit\n";
        goto end;
    }

    if (defined($encryptAbsPath)) {
        unless (-d $encryptAbsPath) {
            print STDERR
            "$0: Error - '$encryptAbsPath' isn't a readable directory\n";
            goto end;
        }
    }
    else {
        my ($licenseDir);
        unless (defined ($titleId)) {
            $titleId = "deadcafe";
        }
        $licenseDir = "$baseName" . "$genLicDirExt";
        unless (setupLicenseDir($licenseDir, $titleId, \$inputEncryptDir)) {
            goto end;
        }
    }
    unless (setupEncryptionDir($encryptAbsPath, %decryptFiles)) {
        print STDERR "$0: Setting up up the encryption directory failed -exit\n";
        goto end;
    }
    if ($verbose) {
        $command = "$genLic <top level directory> -split -dvd";
        print "$0: Directory preparation succeeded\n";
        print "$0: Please run the following command:\n";
        print "        '$command'\n";
    }
    $exitVal = 0;

end:
    unless ($keep) {
        if (-d $decryptDir) {
            $command = "rm -r $decryptDir";
            if (system ($command) != 0)  {
                print STDERR "$0: Removing decrypt directory $decryptDir failed\n";
            }
        }
    }
    exit($exitVal);
} # main

main;
