#!/usr/bin/perl -w
#
# Web Services SAMPLE CODE -- Akamai Technologies, Inc.
# Copyright (c) 2004.  All Rights Reserved.
# Author: Akamai Customer Care 
#
# Your use of this sample application is subject to Akamai's License 
# Agreement, which you should read carefully before proceeding at:
# https://control.akamai.com/portal/content/webservices/docs/script_license.jsp
#
# Complete EdgeControl Web Services Developers guide can be found at:
# https://control.akamai.com/portal/content/webservices/docs/awsv2.jsp
#
# PERL REQUIREMENTS
# -----------------
# perl 5.6.1 or higher
# 
# MODULE REQUIREMENTS
# -------------------
# SOAP-Lite-0.60 or higher (SOAP::Lite)
# libwww-perl-5.76 or higher (LWP)
# HTML-Parser-3.35 or higher (HTML::Parser)
# Crypt-SSLeay-0.51 or higher (Crypt::SSLeay)
# Mime-Base64-2.2 or higher (MIME::Base64)
# IO::Socket::SSL
# Getopt::Long
#use lib '/var/www/html/dev/pankaj_adserver/common/bin';
use FindBin;
use lib $FindBin::Bin;
use strict;
use Getopt::Long qw(GetOptions);
use MIME::Base64;
use PublishECCU;

#--------------------------------
# Command line argument processing
#--------------------------------

my ($debug, $list, $get_info, $delete, $fileid, 
    $new_note, $address,$user,$pwd,$upload,$file,$help);
GetOptions ('list'        => \$list,
            'debug'       => \$debug,
            'get_info'    => \$get_info,
    	    'delete'      => \$delete,
            'file_id=s'   => \$fileid,
            'edit_notes=s'=> \$new_note,
            'edit_email=s'=> \$address,
             'user=s' => \$user,
             'pwd=s' => \$pwd,
            'upload=s'    => \$upload,
            'file=s' => \$file,
            'help'        => \$help);

#------------------
# Argument Checking
#------------------

if ($help) {
    exec("perldoc $0");    
}

#--------------------------
# Prompt: username/password
#--------------------------

# insert your own authentication scheme here.

#print "Akamai EdgeControl Username: $user\n ";
#my $user =<STDIN>;
$user =~ s/\s+//g;

#print "Akamai EdgeControl Password: ";
#my $pass =<STDIN>;
$pwd =~ s/\s+//g;

#--------------------
# Setup SOAP Services 
#--------------------
# setup SOAP::Lite
use SOAP::Lite +trace =>
[transport => sub {
    if ($_[0]->isa('HTTP::Request')) {
        $_[0]->header('Authorization',
                      'Basic ' . encode_base64("$user:$pwd"));
    }
}];

# initialize the service stub
my $service = new PublishECCU;

# !! Import Akamai Customer Care troubleshooting tip !!
# !! uncomment following two lines to enable debugging !!
#
# $service->readable(1);
# $service->on_debug(sub {print @_, "\n";});
                                                                                
# catch faults if any
$service->on_fault(sub {my ($soap, $res) = @_; 
                        die "\nFault ... \n", $res->faultstring,"\n"; });

# SOAP::Lite needs us to setup the XML schemas explicitly.
$service->xmlschema("http://www.w3.org/2001/XMLSchema");

$service->serializer
        ->namespaces
        ->{'https://control.akamai.com/2003/Sep/PublishECCU.xsd'} = 'akapubeccudt';


#-----
# Main
#-----

if ($list) {
    # if --list flag is used, list all ECCU fileIDs on the account
    # GetIds() --takes no input; lists all ECCU file ID's
    # returns an array of integers
    
    my $list_result = $service->getIds();

    print "These are the existing ECCU_file Id's for this account\n";
    for my $ids_info (@$list_result)  { print "$ids_info\n";  }
    exit(0);
}

if ($get_info && $fileid) {
    # if --getinfo flag is used with the --filedid=FILEID
    # GetInfo() --takes fileid as input; Retreive information about 
    # previously uploaded ECCU file
    # returns an integer

    my $retrieveContents=1; # set to 1 if you want to see the uploaded content

    my $getinfo_result = $service->getInfo($fileid, $retrieveContents);

    if ($getinfo_result) {
        print "Fileid: $getinfo_result->{fileId}\n",
              "File Name: $getinfo_result->{filename}\n",
              "Upload Date: $getinfo_result->{uploadDate}\n",
              "Status Update Date: $getinfo_result->{statusUpdateDate}\n",
              "Status Code: $getinfo_result->{statusCode}\n",
              "File Size: $getinfo_result->{fileSize}\n",
              "Notes: $getinfo_result->{notes}\n",
              "Version String $getinfo_result->{versionString}\n",
              "Status Message: $getinfo_result->{statusMessage}\n",
              "Status Change Email: $getinfo_result->{statusChangeEmail}\n",
              "Extended Status Message: $getinfo_result->{extendedStatusMessage}\n",
              "Property Name: $getinfo_result->{propertyName}\n",
 	          "Property Type: $getinfo_result->{propertyType}\n",
	          "Property Name Exact match: $getinfo_result->{propertyNameExactMatch}\n",
	          "md5Digest: $getinfo_result->{md5Digest}\n",
	          "Uploaded By: $getinfo_result->{uploadedBy}\n\n";

        if ($retrieveContents==1) { 
            print "Content: $getinfo_result->{contents}\n\n"; 
        }
	} 
exit(0);
}

if ($delete && $fileid) {
    # if --delete flag is used with the --filedid=FILEID
    # delete() --takes Fileid (integer) as input; Deletes ECCU file with fileid
    # returns a boolean indicating success/failure

    my $ok_txt="ECCU file $fileid succesfully deleted";
    my $err_txt="Could not delete ECCUFile. Please try again";
    my $delete_result;
    
    $delete_result = $service->delete($fileid);
  
    # pass return status to check_results function to print 
    # success/failure (code for function in this file)
    
    check_result($delete_result,$err_txt,$ok_txt);
 
    exit(0);
}

if ($fileid && $new_note) {
    # if --edit_note flag is used with --filedid=FILEID
    # setNotes() --takes fileid (integer) ,notes (string) as input; 
    # Sets notes for uploaded ECCU file
    # returns boolean indicating success/failure
  
    my $ok_txt="Note for $fileid succesfully updated";
    my $err_txt="Could not write note";

    my $setnotes_result = $service->setNotes($fileid, $new_note);

    # pass return status to check_results function to print 
    # success/failure (code for function in this file)
   
    check_result($setnotes_result,$err_txt,$ok_txt);

    exit(0);
}

if ($fileid && $address) {
    # if --edit_address flag is used with the --filedid=FILEID
    # setStatusChangeEmail() --takes fileid (integer), emailaddress (string) 
    # as input; Sets email address associated to a uploaded ECCU file
    # returns boolean indicating success/failure

    my $ok_txt="Emailaddress succesfully updated in $fileid";
    my $err_txt="Could not write new emailaddress";

    my $set_email_result = $service->setStatusChangeEmail($fileid, $address);

    # pass return status to check_results function to print success/failure 
    # (code for function in this file)
    
    check_result($set_email_result,$err_txt,$ok_txt);

    exit(0);
}


  open(FILE, $file) || die "Cannot open: $!\n";
  my $cnt=0;
  while (<FILE>) {
    chomp;
    push(@ARGV,$_);
    $cnt++;
  }
  close(FILE);


if ($upload) {
    # if --upload=filename flag is entered

  my ($filename, $notes, $versionString, $propertyName, $propertyType, 
        $propertyNameExactMatch, $statusChangeEmail,$contents);
    my $err_txt="Could not upload file";
    my $string;

    # open and read the file to be uploaded
#    open (IN, "<$upload") 
#        || die "File $upload not found";
  
#    while (<IN>) {
#       chomp;
        
        # push to argv array so we can parse 
        # it with GetOptions afterwards
#       push(@ARGV, $_);
#   }
    
#    close (IN);

    GetOptions ('filename=s'                   => \$filename,
                'notes=s'                      => \$notes,
	            'versionString=s'               => \$versionString,
                'propertyName=s'               => \$propertyName,
                'propertyType=s'               => \$propertyType,
                'propertyNameExactMatch=s'     => \$propertyNameExactMatch,
                'statusChangeEmail=s'          => \$statusChangeEmail,
                'contents=s'                   => \$contents);

    
    foreach (@ARGV) {
        # add \n again to make this more readable
        $contents.="\n".$_;
    }   
    
    #encode content before passing to upload
    $contents=encode_base64(qq ($contents)); 
 
    # Remove leading spaces
    $filename=~s/^\s+//;
    $notes=~ s/^\s+//;
    $versionString=~ s/^\s+//;
    $propertyName=~ s/^\s+//;
    $propertyType=~ s/^\s+//;
    $propertyNameExactMatch=~ s/^\s+//;
    $statusChangeEmail=~ s/^\s+//;

    # Remove trailing spaces
    $filename=~ s/\s*$//;
    $notes=~ s/\s*$//;
    $versionString=~ s/\s*$//;
    $propertyName=~ s/\s*$//;
    $propertyType=~ s/\s*$//;
    $propertyNameExactMatch=~ s/\s*$//;
    $statusChangeEmail=~ s/\s*$//;

    my $id = $service->upload($filename, $contents, $notes, $versionString, 
                              $propertyName, $propertyType, 
                              $propertyNameExactMatch, $statusChangeEmail);

    my $ok_txt="ECCUfile $id successfully uploaded\n";

    check_result($id,$err_txt,$ok_txt);
  
    # pass return status to check_results function to print 
    # success/failure (code for function in this file)
}
else {
    # not a valid combination of arguments; show documentation
    print "Incorrect Command Line Synatx.  \n\n",
           "usage:  publish_eccu.pl --list| ",
           "[--get_info|--delete|--edit_notes|--edit_email --file_id=integer]",
           " | --upload=\"file\" \n",
           "For more detailed help info, run:  \n\n publish_eccu.pl --help\n";
}


#------------
# Subroutines
#------------

sub check_result {
    # this function checks the return status of an operation 
    # (passed in as input) and outputs the appropriate  
    # ok/error messages (text of messages also taken in as input)

    my ($result,$err_message,$ok_message)=@_;

    if ($result>0) {  
        print "$ok_message\n";
    }
    else {  
        print "$err_message\n";
    }
}
        

__END__

#--------------
# Documentation
#--------------

=cut

=head1 NAME

B<publish_eccu.pl> -- lets you upload, download, modify Enhanced Content Control Utility (ECCU) files

=head1 SYNOPSIS

S<Usage:  B<publish_eccu.pl> --list| [--get_info|--delete|--edit_notes|--edit_email --file_id=integer] | --upload="file">

=head1 EXAMPLES

S<publish_eccu.pl --list>

S<publish_eccu.pl --get_info --file_id=5884>

S<publish_eccu.pl --delete --file_id=5884>

S<publish_eccu.pl --file_id=5884 --edit_notes="This is the text of the new note">

S<publish_eccu.pl --file_id=5884 --edit_email=newaddress@yoursite.com>

S<publish_eccu.pl --upload=eccu_file.txt>

=head1 DESCRIPTION

Akamai Web Services sample perl code. Demonstrate the methods used in PublishECCU:getids(), getInfo(), delete(), setNotes(), setStatusChangeEmail(), upload().

ECCU (Enhanced Content Control Utility) allows you to upload an XML file to the Akamai network that will instruct the edge servers how to refresh your content (by directory, by extension, etc)

=head1 OPTIONS

Command line arguments include:

=over 4

=item --list

Lists all available ECCU FileIds for this account

=item --get_info

Lists ECCU File Info for the specified file_id.  Must be used with the --file_id flag

=item --delete

Deletes the ECCU File for the specified file_id.  Must be used with the --file_id flag

=item --file_id=<file_id>      

Specifies the file_id on which to perform an operation.  Use together with delete, get_info,edit_note, 
edit_email. 

=item --edit_note=<Text of note>

Edits the note text for the specified file_id.  Must be used with the --file_id flag

=item --edit_email=<email address>      

Edits the email address for the specified file_id.  Must be used with the --file_id flag

=item --debug

Shows debuging mode. All headers in the request are displayed. Used with any of the options

=item --upload=<filename of ECCUU XML file>         

Uploads a new ECCU XML file to the Akamai network.  Enter the filename to upload.

The syntax of the file is:

--filename:<Your filename>

--notes:<Your notes>

--versionString:<Your version string>

--propertyName:<Your propertystring>

--propertyType: arltoken or hostheader

--propertyNameExactMatch:true or false

--statusChangeEmail:<Email address for notification>

--contents:

<line 1 of upload code>

<line 2 of upload code>

...
<last line of upload code>

You can change the sequence of the tags but --contents must be the last. Do not add any comments anywhere in this file.

Here is an example of an appropriate file:

--filename=Production Test File2

--notes=test ECCU file

--versionString=1.0

--propertyName=www.mysite.com

--propertyType=hostheader

--propertyNameExactMatch=0

--statusChangeEmail=myemail@mycompany.com

--contents=

<?xml version="1.0"?>

<eccu>

<match:recursive-dirs value="images">

<match:ext value="gif">

<revalidate>1067951939</revalidate>

</match:ext>

</match:recursive-dirs>

</eccu>

=back

=head1 AUTHOR

Customer Care (nsitterl), Akamai Technologies, Inc. (ccare@akamai.com)

=cut

