#!/usr/bin/perl
# download_theme - downloads the theme and verifies its signature
#
# Ken Steele
# Copyright (c) Chumby Industries, 2007-2010
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#

main();

sub main
{
    my $filename = "theme.swf";
    my $location = "/tmp";

    my $URL = $ARGV[0] || die( "Syntax: $0 <url> <md5>\n" );
    my $MD5 = $ARGV[1] || die( "Syntax: $0 <url> <md5>\n" );

    # download theme
    system( "rm -f /tmp/flashplayer.event" );
    $rc = system( "/usr/bin/wget -T 240 --writefpevent -O $location/$filename $URL >/dev/null 2>&1" );
    $rc = $rc >> 8;
    if( $rc )
    {
        exit_with_error( "theme not found\nPlease choose a different theme" );
    }
    
    # compare md5sum    
    my $localMD5 = `md5sum $location/$filename`;
    $localMD5 =~ s/\s+.*//;
    chomp( $localMD5 );
   
    if( $localMD5 ne $MD5 )
    {
        exit_with_error( "checksum failed\nPlease choose a different theme" );
    }
    
    exit_success();
}

sub exit_success
{
    print "<download_theme error=\"success\" />\n";
    exit( 0 );
}

sub exit_with_error
{
    my ($error) = @_;

    open( F, ">/tmp/download_theme.error" );
    print F "$error";
    close( F );
    print "<download_theme error=\"$error\" />\n";

    exit( -1 );
}
