#!/usr/local/bin/php
<?php

  $d = strftime("%m%d%y");
  $fp = popen("/usr/local/pgsql/bin/psql -l", "r");

  // Header Throw Away
  $temp = fgets($fp, 1024);
  $temp = fgets($fp, 1024);
  $temp = fgets($fp, 1024);
  $temp = fgets($fp, 1024);

  while ( !feof($fp) ) {
    $data = explode("|", fgets($fp, 1024));
    $database[] = Trim($data[0]);
  }
  pclose($fp);
  system("mkdir /usr/local/pgsql/backup/$d");

  $fp = fopen("/tmp/$d.sh", "w");
  fputs($fp, "#!/usr/bin/bash\n");

  for ( $y = 0; $y < Count($database) - 3; $y++ ) {
    if ( !strstr($database[$y], "template") ) {
      echo "Database: $database[$y]\n";
      $conn = pg_Connect("host=localhost user=postgres dbname=$database[$y]");
      $result = pg_Exec($conn, "SELECT relname FROM pg_class WHERE relkind='r' and relname !~ '^pg_' and relname !~ '^pga_' and reln
ame !~ '^pgadmin_';");
      $rows = pg_NumRows($result);
      for ( $x = 0; $x < $rows; $x++ ) {
        $data = pg_Result($result, $x, 0);
        $command = "/usr/local/pgsql/bin/pg_dump -t $data $database[$y] > /usr/local/pgsql/backup/$d/$database[$y].$data.sql";
        fputs($fp, "$command\n");
      }
      pg_FreeResult($result);
      pg_Close($conn);
    }
  }
  fputs($fp, "tar cvf /tmp/$d.tar /usr/local/pgsql/backup/$d/*\n");
  fputs($fp, "rm -rf /usr/local/pgsql/backup/*\n");
  fputs($fp, "rm /tmp/$d.sh\n");
  fputs($fp, "tar cvfy /dev/st0 /tmp/$d.tar\n");
  fputs($fp, "rm /tmp/$d.tar\n");
  fputs($fp, "touch /tmp/backup.last\n");

  fclose($fp);
  system("chmod u+x /tmp/$d.sh");
  system("/tmp/$d.sh &");
?>