#!/usr/bin/perl

use strict;

my $dateInFile;
my @filelist;
my $latestDate;
my $url = "http://the-sun.on.cc";
my $platformStr;

getSdate();
getFolder();
getLatestDate();
getPlatform();

sub getSdate(){
  my $sdate = '/data/site/tsn/js/sdate.js';
  @filelist;

  open(IN, "<".$sdate);
  while(<IN>) {
    $dateInFile .= $_;
  }
  $dateInFile = substr $dateInFile, -11, 8;
  close(IN);
}

sub getFolder(){
  my $directory = '/data/site/tsn/cnt/good_news/';

  opendir(DIR, $directory);

  while(my $file = readdir(DIR)){
    if($file =~ /^[+-]?\d+$/){
      if(&checkContent($directory.$file."/index.html")==1){
	push(@filelist, $file);
      }
    }
  }
  closedir(DIR);
  @filelist = reverse(sort(@filelist));
}

sub checkContent(){
  my $curFile = shift;
  my $fileContent = "";
  open(IN, "<".$curFile);
  while(<IN>) {
    $fileContent .= $_;
  }
  close(IN);
  $fileContent =~ s/\r|\n//g;
  $fileContent =~ s/[^a-zA-Z0-9]//go;
  if($fileContent eq ""){
    return 0;
  }
  return 1;
}

sub getLatestDate(){
  for(@filelist){
    if($dateInFile>=$_){
      $latestDate = $_;
      last;
    }
  }
}

sub getPlatform(){
  my $platformPath = '/data/site/platform';
  open(IN, "<".$platformPath);
  while(<IN>) {
    $platformStr .= $_;
    $platformStr =~ s/\r|\n//g;
  }
  close(IN);

  if($platformStr eq "DEV"){
    $url = 'http://the-sun.on.cc';
  }

  if($platformStr eq "UAT"){
    $url = 'http://tsn.preview06.uat.cms/cnt/good_news/'.$latestDate.'/index.html';
  }

  if($platformStr eq "LIVE_PREVIEW"){
    $url = 'http://tsn.preview.prod.cms/cnt/good_news/'.$latestDate.'/index.html';
  }

  if($platformStr eq "LIVE"){
    $url = 'http://the-sun.on.cc/cnt/good_news/'.$latestDate.'/index.html';
    #$url = 'http://epaper.on.cc/cgi-bin/view.cgi?pub=tsn&pub_sect=gdn';
  }
}

print "Content-type: text/html\n\n";
print
"<html lang='zh-hk'>\n".
"<head>\n".
"<meta name='title' content='tsn'/>\n".
"<meta name='description' content='on.cc'/>\n".
"<meta HTTP-EQUIV='Content-Type' Content='text-html; charset=utf-8'>\n".
"<title>tsn</title>\n".
"<script>\n".
"var iOS = (navigator.platform.indexOf(\"iPhone\") != -1) || (navigator.platform.indexOf(\"iPad\") != -1) ? true : false;\n".
"var android = (navigator.platform.indexOf(\"armv7l\") != -1) ? true : false;\n".
"    if (iOS || android) {\n".
"        document.write('瀏覽器會自動跳至下載頁面 或 <a href=\"http://the-sun.on.cc/cnt/good_news/".$latestDate."/index.html\">按此</a>');\n".
"        window.location = \"http://the-sun.on.cc/cnt/good_news/".$latestDate."/index.html\";\n".
"   }\n".
"    else{\n".
#"        window.location = \"http://epaper.on.cc/cgi-bin/view.cgi?pub=tsn&pub_sect=gdn\";\n".
"        window.location = \"http://the-sun.on.cc/cnt/good_news/".$latestDate."/index.html\";\n".
"    }\n".
"</script>\n".
"</head>\n".
"<body>\n".
"</body>\n".
"</html>\n";
exit;
