<?php
//   a) Return lsit of existing session backups
//  b) admin can choose which session to restore
// c) do the restore (several steps, dir/file/mysqlData creation

require("phpVars.php");

header('Content-Type: text/plain; charset=iso-8859-1');
$ierr=0;

  $sessName='';
  $todo=0;
  $refnum=0;

 foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     if ($avar=='SESSION') $sessName=trim($oof);
     if ($avar=='TODO') $todo=trim($oof);
     if ($avar=='REFNUM') $refnum=trim($oof);
 }


 if (!file_exists($backup_dir)) {
      print "-Sorry. No sessions backup directory: $sbackup_dir";
      return 0 ;
}

// return list of available backups
if ($todo==0) {
  $stuff='';

  $idir=opendir($backup_dir);
  while (!($filename= readdir($idir)) === FALSE) {

   if ($filename=='.' || $filename=='..') continue ;
   if (!is_file($backup_dir . $filename)) {           // found a directory, see if mysqlXXX file exists
//$stuff.="\n dir: $backup_dir" . "$filename \n ";

      $idir2=opendir($backup_dir . $filename) ;
      $igot=0;
      while (!($filename2= readdir($idir2)) === FALSE) {
        if ($filename2=='.' || $filename2=='..') continue ;
//        $stuff.="\n ff: ". $backup_dir . $filename . '/' . $filename2 ." \n ";
         $igot++ ;
         if (substr($filename2,0,6)=='mysql_')  {
            $adate=substr($filename2,6);
            $adate0=explode('.',$adate);
            $zz=$adate0[0];
            if (is_numeric($zz)) {
              $realdate=date('r',$adate0[0]);
              $stuff.=   $filename . ';'  . $adate0[0]  . ';' . $realdate .   "  | ";
            }
         }
      }     // while
      closedir($idir2);

      if ($igot==0) {               // empty
           $stuff .=   $filename . " ; 0  ; No backups   | " ;
      }

   }                  // backupdir if
  }                   // while $filename

 closedir($idir);

 print $stuff ;
 exit ;

}


//  remove an empty directory
if ($todo==4) {
  $sessBdir=$backup_dir . $sessName .'/' ;       // all backups for a session are in same (session specific) directory
  if (!file_exists($sessBdir)) {
      print "Sorry. No  such backup directory: $sessBdir";
      exit ;
  }
  $qq=rmdir($sessBdir);
  if ($qq) {
     print "Directory removed  ($sessName) ";
  } else {
     print "Error removing directory $sessBdir <p />";
     print_r(error_get_last());
  }
  exit ;
}

//  remove a backup
if ($todo==3) {
 $stuff='<h4>Details...</h4> ';

 $ndel=0;
  $sessBdir=$backup_dir . $sessName .'/' ;       // all backups for a session are in same (session specific) directory
  if (!file_exists($sessBdir)) {
      print "-Sorry. No  backup directory for session: $sessBdir";
      exit ;
  } else {
     print 'Removing backup of ' . $sessName . ', refnum = ' . $refnum . ' (date: ' . date('r',$refnum) . ') ' . "\n <p/> ";
  }
  $stuff='<h4>Details...</h4> ';
  $idir=opendir($sessBdir);
  while (!($filename= readdir($idir)) === FALSE) {
     if ($filename=='.' || $filename=='..') continue ;
     if (!is_file($sessBdir . $filename)) continue ;

     $i1=strpos($filename,'_');
     $i2=strpos($filename,'$');
     if ($i2===false) $i2=strpos($filename,'.');
     $a2=substr($filename,$i1+1,$i2-(1+$i1));
     if ($a2!=$refnum) continue ;

     $afile=$sessBdir . $filename ;
     $qq=unlink($afile);

     if (!$qq) {
       print "Error removing $afile ";
       print_r(error_get_last());
       print "<p /> $stuff ";
       exit;
     }
    $stuff .= " Delete: $filename <br/> ";
     $ndel++ ;
  }
  print "$ndel files removed <p /> $stuff ";
  exit ;
}


// todo=2: restore a particular session
$descriptor='';
$sqldb='';
$pinfos[0]=0;
$sessions[0]=0;
$sessBdir=$backup_dir . $sessName .'/' ;       // all backups for a session are in same (session specific) directory
if (!file_exists($sessBdir)) {
      print "-Sorry. No  backup directory for session: $sessBdir";
      exit ;
} else {
   print 'Restoring session ' . $sessName . ', refnum = ' . $refnum . ' (date: ' . date('r',$refnum) . ') ' . "\n <p/> ";
}

$stuff='<h4>Details...</h4> ';
$idir=opendir($sessBdir);
while (!($filename= readdir($idir)) === FALSE) {
   if ($filename=='.' || $filename=='..') continue ;
   if (!is_file($sessBdir . $filename)) continue ;

   $i2=strpos($filename,'$');

   if (substr($filename,0,6)=='mysql_') {
       $i2=strpos($filename,'.');
        $a1=substr($filename,6,$i2-6);
        if ($a1!=$refnum) continue ;
        $sqldb=$filename ;
   }
      if (substr($filename,0,11)=='descriptor_') {
        $a1=substr($filename,11,$i2-11);
        if ($a1!=$refnum) continue ;
        $a2=substr($filename,$i2+1);
        $descriptor=array($a2,$filename) ;
   }

   if (substr($filename,0,6)=='pinfo_') {
        $a1=substr($filename,6,$i2-6);
        if ($a1!=$refnum) continue ;
        $a2=substr($filename,$i2+1);
        $pinfos[]=array($a2,$filename) ;
   }

   if (substr($filename,0,8)=='session_') {
        $a1=substr($filename,8,$i2-8);
        if ($a1!=$refnum) continue ;
        $a2=substr($filename,$i2+1);
        $sessions[]=array($a2,$filename) ;
   }

}

// prelim: connect to mysql
$link=mysqli_connect('localhost','dsurveyAdmin','admin');
if (!$link) {
   print ' - Error. Could not connect to mysqli (with username=`dsurveyAdmin` and password=`admin`): ' . mysqli_error() . "<p /> $stuff " ;
   print "<p /> $stuff ";
   exit ;
}

// 1a: create /sessions/sessname exist?
$dadir=$sessions_dir . $sessName . '/' ;

$qq=file_exists($dadir);
if (!$qq) {                        // no such directory, create it
  $qq2=mkdir($dadir);
  if (!$qq2)    {
     print "\n \n Error: unable to recreate session directory: $dadir <p /> $stuff   ";
     print "<p /> $stuff ";
     exit ;
  }
  $stuff .= "\n  Session directory created: $sessName  <br/> ";
} else {
  $stuff .="\n  Using existing session directory: $sessName   <br/>";
}

// 1b: create /pinfo/sessname exist?
$pdir=$pinfo_dir . $sessName . '/' ;
$qq=file_exists($pdir);
if (!$qq) {                        // no such directory, create it
  $qq2=mkdir($pdir);
  if (!$qq2)    {
     print "\n \n Error: unable to recreate session pinfo directory: $pdir <p /> $stuff    ";
     exit ;
  }
  $stuff .= "\n  Session  pinfo directory created: $sessName <br/> ";
} else {
    $stuff .="\n  Using existing session pinfo directory: $sessName  <br/>";
}

//  2:copy descriptor file
$fromfile=$sessBdir . $descriptor[1];
$qq=file_exists($fromfile);
if (!$qq) {
     $stuff .= "\n \n Error: no backup session-descriptor file:  $fromfile  <p /> $stuff   ";
     exit ;
}

$tofile=$sessions_dir . $descriptor[0] ;
$qq2=file_exists($tofile);

$qq=copy($fromfile,$tofile);
if (!$qq) {
     print "\n \n Error: unable to restore session-descriptor file:  $tofile <p /> $stuff   ";
     exit ;
} else {
     if ($qq2) {
        $stuff .= "\n \n  ... Session descriptor file overwritten:  $descriptor[0]  <br/> ";
     } else {
        $stuff .= "\n \n  ... Session descriptor file created:  $descriptor[0]  <br/> ";
     }
}

//  3) recreate sql database
$sqlfile=$sessBdir . $sqldb ;
$aexists=file_exists($sqlfile);
if (!$aexists) {
     print "-Sorry. Unable to find mySql database backup file: $sqlfile  <p /> $stuff  ";
     exit ;
}
$stuff .= "\n Recreating mySql using: $sqldb <br />" ;

$mdata=$hdrMysql . $sessName ;

// remove old database, then create one (with no data)
mysqli_query($link,"DROP DATABASE IF EXISTS " . $mdata)  ;
$qq=mysqli_query($link,"CREATE DATABASE  " . $mdata)  ;
if (!$qq) {
  print " ... Error: creating mysql database: " . mysql_error() . " <p /> $stuff  ";
  return 1 ;
}
$qq=mysqli_select_db($link,$mdata);

$file=fopen($sqlfile,'r');
if (!$file) return ' ...  Error: problem opening mySql backupfile: ' . $sqlfile  . "  <p /> $stuff " ;
$query=fread($file,filesize($sqlfile));
if (!$query) return  ' ...  Error: unable to read from mySql backupfile: ' . $sqlfile  . " <p /> $stuff  ";
fclose($file);

// now, restore using contents of the mysql backup file
$foo=restoreDbBackup($link,$query);
if (substr($foo,0,1)=='-') {
    print " ... Error in restoring mySql data from $sqlFile : $foo   <p /> $stuff  ";
} else {
        $stuff .= ' ... mySql data restored (# of  sql commands= ' .  $foo  . ')' . '<br/> ' ;
}

//  4) restore _pinfo files
$stuff .= "Restoring " . (count($pinfos)-1) . "  pinfo files  <br/>";
for ($j=1 ;$j<count($pinfos);$j++) {
  $p1=$pinfos[$j];
  $tofile=$pdir . $p1[0];
  $fromfile=$sessBdir . $p1[1];

  $qq=file_exists($fromfile);
  if (!$qq) {
     print "\n \n ... Error: no backup pinfo file:  $fromfile  <p /> $stuff  ";
     exit ;
  }

  $qq2=file_exists($tofile);

  $qq=copy($fromfile,$tofile);
  if (!$qq) {
     print "\n \n ... Error: unable to restore pifno file:  $tofile   <p /> $stuff  ";
     exit ;
  } else {
     if ($qq2) {
        $stuff .= "\n ... ($j)  pinfo file overwritten:  $p1[0]   <br/> ";
     } else {
       $stuff .= "\n  ...  ($j) pinfo file created: $p1[0]   <br/> ";
     }
  }
}


//  5) restore session files
$stuff .= "Restoring " . (count($sessions)-1) . "  session files <br/>";
for ($j=1 ;$j<count($sessions);$j++) {
  $p1=$sessions[$j];
  $tofile=$dadir . $p1[0];
  $fromfile=$sessBdir . $p1[1];

  $qq=file_exists($fromfile);
  if (!$qq) {
     print "\n \n ... Error: no backup session file:  $fromfile  <p /> $stuff  ";
     exit ;
  }

  $qq2=file_exists($tofile);

  $qq=copy($fromfile,$tofile);
  if (!$qq) {
     print "\n \n ... Error: unable to restore session file:  $tofile <p /> $stuff ";
     exit ;
  } else {
     if ($qq2) {
        $stuff .= "\n ... ($j)  session file overwritten:  $p1[0]    <br/> ";
     } else {
        $stuff .= "\n ...  ($j) session file created: $p1[0]      <br/> ";
     }
  }
}

print "Successful restore! <p /> $stuff ";
exit;

?>
