<?php
//vim: ts=2 sw=2

include_once "../app/config.php";
include_once "../app/utils.php";
include_once "../app/migration.php";

class DeploymentController {
  public function run() {
    $docRootPath = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
    setupIndex($docRootPath, '', Config::$graphicsAsWebRoot);

    // make sure index.html is setup in both http and https folders
    if (endsWith($docRootPath, 'public'))
      $docRootPath = substr($docRootPath, 0, -strlen('public'));
    else
      $docRootPath = join('/', array($docRootPath, 'public'));
    setupIndex($docRootPath, '', Config::$graphicsAsWebRoot);
    
    //apply db migrations 
    Migration::instance()->run();
    
    //set up cpt auth data for phpliteadmin
    $this->setupPhpLiteAdmin();

    $this->cleanup();

    sync();

    die('done');
  }

  protected function cleanup() {
    $grDataPath = join('/', array(cptBaseDir(), 'app', 'grdata'));
    $itDir = new RecursiveDirectoryIterator($grDataPath, RecursiveDirectoryIterator::SKIP_DOTS);
    $it = new RecursiveIteratorIterator($itDir, RecursiveIteratorIterator::CHILD_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD);
    foreach($it as $path => $dir)
    {
      if (strpos($path, '_outdated_') === false)
        continue;

      error_log('clean up ' . $path);
      if ($dir->isDir())
        rmdir($path);
      else
        unlink($path)
    }
  }
  
  protected function setupPhpLiteAdmin() {
    $u = new User();
    if ($u->find("admin"))
        updatePhpAdminAuth($u->attr("salt"), $u->attr("checksum"));
  }
}

$controller = new DeploymentController();
$controller->run();
    
?>