#!/usr/bin/perl
#
#  copypng [options] SRCFILE DSTFILE
#
#  Copyright (c) 2015 Apple Inc.
#  All rights reserved.
#
#  This script copies one PNG image file from the provided source file
#  paths to the destination path.  The destination file may have a different
#  name from the source files.  This script can optionally optimize the images
#  and remove metadata as they are being copied.
#

use warnings;
use strict;

use File::Spec::Functions qw(rel2abs);
use File::Basename;

# Prefer pngcrush from the same directory over running a search
my $dir = dirname(rel2abs($0));
my $PNGCRUSH = "$dir/pngcrush";
if (not -f $PNGCRUSH) {
    $PNGCRUSH = `xcrun -f pngcrush`;
}
chomp $PNGCRUSH;

my $compress = 0;
my $stripPNGText = 0;
my @FILES = ();

# Gather command line options.
while( @ARGV ) {

    $_ = shift @ARGV;

    next if ( $_ eq "" );

    if ( $_ =~ /-strip-PNG-text/ ) {
        $compress = 1;
        $stripPNGText = 1;
        next;
    }
    if ( $_ =~ /-skip-PNGs/ ) {
        $compress = 0;
        next;
    }
    if ( $_ eq "-compress" ) {
        $compress = 1;
        next;
    }
    if ( $_ =~ /^-/ ) {
        print "WARNING: Ignoring unknown option $_";
        next;   # unknown option
    }
    
    # save files
    push @FILES, $_;
}

my $SRCFILE = shift @FILES;    # first file is source
my $DSTFILE = shift @FILES;    # then dest

if ( ! -f $SRCFILE ) {
    print STDERR "ERROR: Can't find $SRCFILE\n";
    exit 1;
}
if ( !length($DSTFILE) ) {
    print STDERR "ERROR: Destination file missing\n";
    exit 1;
}

# delete the destination file if it exists
if ( -f $DSTFILE ) {
    unlink($DSTFILE) or die "Could not delete $DSTFILE: $!\n";
}

my $DSTDIR = `dirname "$DSTFILE"`;
chomp $DSTDIR;
$DSTDIR .= "/";

my @args;

if ( $compress ) {
    @args = ( $PNGCRUSH, "-q", "-iphone", "-f", "0" );
    if ( $stripPNGText ) {
        push ( @args, "-rem", "text" );
    }
    push ( @args, $SRCFILE, $DSTFILE );

} else {
    @args = ( "cp", "$SRCFILE", "$DSTFILE" );
}

# system()'s return value is the exit status encoded in the format for wait() - 
# a tuple that's a 16-bit number where the high byte is the exit status 
my $retval = system(@args) >> 8; 
if ( $retval != 0 ) {
    print STDERR "ERROR: Failed to run @args\n";
    exit $retval;
}