#!/usr/bin/perl
use strict;

gen_exception_report();

sub gen_exception_report {
    my $db_name = $ARGV[0] || return usage("missing database name");
    my $file_id = $ARGV[1] || return usage("missing file_id");

    my $dest    = "/tmp/";
    my $sqldump = qq(mysqldump --tab=$dest "--where=file_id=$file_id and product_id is null or product_id=0" -uroot $db_name sale 2>&1);

    my $sql_err = `$sqldump`;
    if ( $sql_err ne '' ) {
        return usage($sql_err);
        return undef;
    }

    my $header = join(
        "\t", qw(sale_id
          file_id
          import_status
          product_id
          product_type
          format_type
          media_type
          date_begin
          date_end
          service_product_id
          client_product_id
          upc
          isrc
          artist_name
          album_name
          track_name
          label_name
          track_num
          units
          price
          currency_code
          conversion_rate
          country_code
          line_num
          map_id
          date_created
          date_modified)
    );

    my $header_file = "/tmp/header.txt";
    open( HDR, ">$header_file" ) or die "couldn't open header file ($header_file) for writing";
    print HDR $header . "\n";
    close(HDR);

    my $final_file = "/tmp/${db_name}_FILE_${file_id}_exceptions.txt";
    system("cat $header_file /tmp/sale.txt > $final_file; rm -rf /tmp/sale.txt /tmp/sale.sql");
    print "File is $final_file\n";
}

sub usage {
    my $err = shift;

    print "ERROR: $err\n";
    print "Usage (run as root): $0 DB_NAME FILE_ID\n";

    return 1;
}
