#!/usr/bin/perl
#
# Thie program monitors downloads and selects a random mirror, partially
# based on priority.  Database tables used: mirrors, downloads.
# Supported parameters: pkg, rel.

use CGI qw/:standard/;
use DBI;
#use Apache::DBI;

use constant READ_QUERY =>
  'SELECT bzip2,gzip,compress,zip,version,tag,uuid,fn,enabled FROM downloads WHERE pkg = ? AND tag = ? AND src = 1 ORDER BY version ASC';
#----------------------------------------------------------------------------
my %types = (
  'exe', 'application/octet-stream',
  'tar', 'application/x-tar',
  'txt', 'text/plain',
  'bz2', 'application/x-bzip2',
  'gz', 'application/x-gzip',
  'Z', 'application/x-compressed'
);
my $data = undef;
#----------------------------------------------------------------------------
sub TypeFlagMap($);
sub GetType($);
sub GetData($);
sub Main();
#----------------------------------------------------------------------------
exit Main();
#----------------------------------------------------------------------------
sub TypeFlagMap($)
{
  my $Flags = $_[0];
  return 'bz2' if ( $Flags->{'bzip2'} );
  return 'gz' if ( $Flags->{'gzip'} );
  return 'Z' if ( $Flags->{'compress'} );
  return 'zip' if ( $Flags->{'zip'} );
  return '';
}
#----------------------------------------------------------------------------
sub GetType($)
{
  my $t = undef;
  my $Ref = $_[0];
  my $type = TypeFlagMap($Ref);
  if ( $Type ne '' ) { # Resolved?
    $t = $types{$Type};
  } else { # Not resolved, look at the filename instead
    my @parts = split(m/\./, $Ref->{fn});
    $t = $parts[-1] if ( defined($parts[-1]) );
  }

  if ( defined($t) ) {
    if ( exists($types{$t}) ) {
      return $types{$t};
    } else {
      $data = sprintf("FAIL: Missing type for %s\n", $t);
    }
  } else {
    $data = sprintf("FAIL: Bad entry: %s\n", Dumper $Ref);
  }
  return 'txt';
}
#----------------------------------------------------------------------------
sub GetData($)
{
  my $data = '';
  my $FileName = $_[0];
  if ( open(my $h, '< ' . $FileName) ) {
    my $line = undef;
    binmode($h);
    while ( $line = <$h> ) {
      $data .= $line;
    }
    close($h);
  }
  return $data;
}
#----------------------------------------------------------------------------
sub Main()
{
  my $ret = 1;

  my $db = 'ddrp_daybo';
  my $host = 'sql.daybologic.co.uk';
  my $user = 'ddrp_dlsite_dl';
  my $pass = 'T2qQ%bG+m';
  my $connectionInfo="dbi:mysql:$db;$host";
  my $dbh;
  my $pkg = param('pkg');
  my $tag = param('tag');

  $dbh = DBI->connect(
    $connectionInfo,
    $user,
    $pass
  );

  $ret = 0;

  if ( $dbh ) {
    my $sth = $dbh->prepare(READ_QUERY());
    if ( $sth ) {
      my $n = $sth->execute($pkg, $tag);
      if ( $n ) {
        while ( my $ref = $sth->fetchrow_hashref() ) {
          next unless ( $ref->{'enabled'} );
          #printf("UUID: \{%s\}, version: %s, tag: %s, filename: %s\n", $ref->{'uuid'}, $ref->{'version'}, $ref->{'tag'}, $ref->{'fn'});
          print header(-type => GetType($ref));
          unless ( defined($data) ) {
            $data = GetData($Ref->{'fn'});
          }
          print $data;
        }
      }
      $sth->finish();
    }
    $dbh->disconnect();
  } else {
    print "Disconnected.\n";
  }

  return $ret;
}
#----------------------------------------------------------------------------

