<?php

$options = getopt('tn:rs:d:h:u:p:');
$srcPath  = isset($options['s'])? $options['s']: '/data/violet_bak/';
$destPath = isset($options['d'])? $options['d']: '/data/violet/';
$host = isset($options['h'])? $options['h']: '115.84.178.137';
$user = isset($options['u'])? $options['u']: 'violet';
$pass = isset($options['p'])? $options['p']: 'bk,,123~~';
$rcs = array_key_exists('r', $options);
umask(0);

function execSQL($sql) {
  $dbh = new PDO('mysql:host='.$GLOBALS['host'].';dbname=tvtl', $GLOBALS['user'], $GLOBALS['pass']);
  echo "ExecSQL '$sql'\n";
  return $dbh->query($sql);
}

function mycopy($filename, $inf = 'Copy') {
  $src = $GLOBALS['srcPath'] . $filename;
  $dest = $GLOBALS['destPath'] . $filename;
  if ((!$GLOBALS['rcs'] && file_exists($dest)) || !file_exists($src)) return;
  if (is_dir($src)) copydir($src, $dest, $inf);
  else copyfile($src, $dest, $inf);
}

function copydir($src, $dest, $inf) {
  createdir($dest);
  foreach (scandir($src) as $name) {
    if ($name=='.' || $name=='..') continue;
    $src1 = $src.'/'.$name;
    $dest1 = $dest.'/'.$name;
    if (is_dir($src1)) copydir($src1, $dest1, $inf);
    else copyfile($src1, $dest1, $inf, false);
  }
}

function createdir($dir) {
  if (file_exists($dir)) return;
  echo "Create $dir\n";
  mkdir($dir, 0777, true);
}

function copyfile($src, $dest, $inf, $crdir = true) {
  if ($GLOBALS['rcs'] && file_exists($dest) && filesize($src)==filesize($dest)) return;
  if ($crdir) createdir(substr($dest, 0, strrpos($dest, '/')));
  echo "$inf $dest\n";
  copy($src, $dest);
  touch($dest, filemtime($src));
}
