#!/usr/bin/perl

use strict;
use warnings;
use CGI;
use LWP::Simple;
use Cwd 'abs_path';
use File::Basename;
my $dirname = dirname(abs_path(__FILE__));

my $cgi  = new CGI;
my $id   = $cgi->param('i') || 0;
my $host = $cgi->param('h') || '';
my $path = $cgi->param('p') || '';
my $name = $cgi->param('n') || '';
my $test = $cgi->param('t') || '';

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
$year += 1900;
$mon  = ($mon  > 9 ? $mon  : "0$mon");
$mday = ($mday > 9 ? $mday : "0$mday");
$hour = ($hour > 9 ? $hour : "0$hour");
$min  = ($min  > 9 ? $min  : "0$min");
$sec  = ($sec  > 9 ? $sec  : "0$sec");
my $referer = $cgi->referer() || '';
my $useragent = $cgi->user_agent() || '';
#print ">>${dirname}/log.txt\n";
open(my $logfd, ">>${dirname}/log.txt");
print $logfd "[${year}-${mon}-${mday} ${hour}:${min}:${sec}] id=${id} host=${host} path=${path} name=${name} referer=${referer} useragent=${useragent}\n";
close($logfd);

unless (($id || $path) && $name) {
  print $cgi->header(
    -type=>'text/plain; charset=UTF-8',
    -status=> '400 Bad Request'
  );
  print "400 Bad Request\n";
  exit(0);
}

my $url = ($id ? "https://rsi-aod-dd.akamaized.net/${host}/${id}.mp3" : ($host ? "http://${host}.rsi.ch${path}" : "http://s3-ch.swisstxt.ch${path}"));

# Create a user agent object
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->agent("PodcastDownload/0.1");

# Create a request
my $req = HTTP::Request->new(GET => $url);

# Pass request to the user agent and get a response back
my $res = $ua->request($req);

# Check the outcome of the response
if ($res->is_success) {
  $res->header('Content-Disposition' => 'attachment; filename="'.$name.'"');
  print $res->headers()->as_string;
  print "\n";
  if ($test) {
    print "Remove 't=$test' from query string to see the content of $url\n";
  } else {
    print $res->content;
  }
} else {
  print $cgi->header(
    -type=>'text/plain; charset=UTF-8',
    -status=> $res->status_line
  );
  print $res->status_line, "\n";
}
