<?php

$server_root = "/srv/www/tvtl/web/uploads/resources";
$local_root = "/srv/www/tvtl/web/uploads/previews";

require_once("ftp.php");
$ftp = new PHP_FTP("115.84.179.206", "baigiang", "baigiang");
umask(0);
if (@$argv[2] == NULL) exit();

for ($c = $argv[1]; $c < $argv[2]; $c++) {
  $start = $c * 1000;
  $end = ($c+1) * 1000;
  echo date("H:i:s")." Update from $start to $end\n";
  $dbh = new PDO('mysql:host=210.245.80.71;dbname=tvtl', 'tvtl2007', 'tVtL2007remote', array( PDO::ATTR_PERSISTENT => false));
  $stmt = $dbh->prepare(
    "select pr_id, pr_category, pr_playername, pr_type from tblpresentation ".
    "where pr_status<2 and pr_id>=$start and pr_id<$end");
  $stmt->execute();

  while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
    list($pr_id, $pr_cat, $pr_player, $pr_type) = array_values($row);
    $path = "$local_root/$pr_cat/$pr_id";
    if (!file_exists($path)) mkdir($path, 0777, true);

    if ($pr_type == 'pdf') {
      $pos = strrpos($pr_player, '/');
      $server_file = "$server_root/$pr_cat/$pr_id/$pr_player.swf";
      $local_file  = "$local_root/$pr_cat/$pr_id/".($pos? substr($pr_player, $pos + 1): $pr_player).".swf";
      if (!file_exists($local_file)) {
        if ($pos && $ftp->size($server_file)==-1) $server_file = "$server_root/$pr_cat/$pr_id/".substr($pr_player, $pos + 1).".swf";
        $ftp->get($server_file, $local_file);
      }
    }
    
    if ($pr_type == 'doc' || $pr_type == 'docx') {
      $server_file = "$server_root/$pr_cat/$pr_id/preview.swf";
      $local_file  = "$local_root/$pr_cat/$pr_id/preview.swf";
      if (!file_exists($local_file)) {
        $ftp->get($server_file, $local_file);
      }
    }

    if ($pr_type == 'ppt' || $pr_type == 'pptx' || $pr_type == 'gsp' || $pr_type == 'cg3') {
      $server_dir = "$server_root/$pr_cat/$pr_id/images";
      $local_dir  = "$local_root/$pr_cat/$pr_id/images";
      if (!file_exists($local_dir)) {
        $ftp->dget($server_dir, $local_dir);
      }
    }

    if ($pr_type == 'xls' || $pr_type == 'xlsx') {
      $server_dir = "$server_root/$pr_cat/$pr_id/preview_files";
      $local_dir  = "$local_root/$pr_cat/$pr_id/preview_files";
      $server_file = "$server_root/$pr_cat/$pr_id/preview.html";
      $local_file  = "$local_root/$pr_cat/$pr_id/preview.html";
      if (!file_exists($local_file)) {
        $ftp->get($server_file, $local_file);
        $ftp->dget($server_dir, $local_dir);
      }
    }
  }
}

echo "\nBackup finish at ".date("H:i:s")."\n\n";
