#!/usr/bin/perl

use strict;
use CGI;
use File::Basename;
use lib dirname( __FILE__ ) . '/lib';
use rddb;

my $status = 'ERROR';
my $errorstring = 'unknown';
my $responsecode = 500;
my @dropboxes = ();

my $q = CGI->new;

my $username = $q->param('LOGIN_NAME');
my $token = $q->param('PASSWORD');

my $dbh;
($dbh, $status, $errorstring) = rddb::opendb();
if(defined $dbh) {
  my $result;
  ($result, $status, $errorstring) = rddb::check_token($dbh, $username, $token);
  if($result == 1) {
    $responsecode = 200;
    @dropboxes = rddb::get_dropboxes($dbh, $username);
  } elsif($result == 0) {
    $responsecode = 403;
  } else {
    $responsecode = 500;
  }
  rddb::closedb($dbh);
}

print "Content-type: application/xml\n\n";

if($responsecode != 200) {
  print "<RDWebResult>\n";
  print "  <ResponseCode>" . $responsecode . "</ResponseCode>\n";
  print "  <ErrorString>" . $errorstring . "</ErrorString>\n";
  print "</RDWebResult>\n";
} else {
  print "<dropboxList>\n";
  for my $href (@dropboxes) {
    print "  <dropbox>\n";
    print "    <name>" . $href->{'NAME'} . "</name>\n";
    print "    <group>" . $href->{'GROUP'} . "</group>\n";
    print "    <path>" . $href->{'PATH'} . "</path>\n";
    print "    <to_cart>" . $href->{'TO_CART'} . "</to_cart>\n";
    print "  </dropbox>\n";
  }
  print "</dropboxList>\n";
}