<?php

date_default_timezone_set('UTC');

$OLD_PWD = $_SERVER['PWD'];

// work from lib directory
chdir(dirname($argv[0]));

if ($argv[0] === './pre-install.php' || $_SERVER['PWD'] !== $OLD_PWD) {
  // pwd doesn't resolve symlinks
  $LIB_DIR = $_SERVER['PWD'];
} else {
  // windows doesn't update $_SERVER['PWD']...
  $LIB_DIR = getcwd();
}

$APP_DIR = dirname($LIB_DIR);
$HTDOCS_DIR = $APP_DIR . DIRECTORY_SEPARATOR . 'htdocs';
$CONF_DIR = $APP_DIR . DIRECTORY_SEPARATOR . 'conf';
$HTTPD_CONF = $CONF_DIR . DIRECTORY_SEPARATOR . 'httpd.conf';
$PHP_INI = $CONF_DIR . DIRECTORY_SEPARATOR . 'php.ini';


// add lib directory to include path
$include_path = get_include_path() . PATH_SEPARATOR . $LIB_DIR;


// create conf directory if it doesn't exist
if (!is_dir($CONF_DIR)) {
  mkdir($CONF_DIR, 0755, true /*recursive*/);
}

file_put_contents($PHP_INI, '
  ;; autogenerated at ' . date('r') . '

  ; add template lib directory to include path
  include_path = "' . $include_path . '"
');

// write apache configuration
file_put_contents($HTTPD_CONF, '
  ## autogenerated at ' . date('r') . '

  <IfModule mod_php5.c>
    # add template lib directory to include path
    php_value include_path "' . $include_path . '"
  </IfModule>

  <IfModule mod_php7.c>
    # add template lib directory to include path
    php_value include_path "' . $include_path . '"
  </IfModule>

  # template alias for css/js/images
  Alias /theme ' . $HTDOCS_DIR . '

  # permissions for template directory
  <Location /theme>
    # apache 2.2
    <IfModule !mod_authz_core.c>
      Order allow,deny
      Allow from all

      <LimitExcept GET>
        Deny from all
      </LimitExcept>
    </IfModule>

    # apache 2.4
    <IfModule mod_authz_core.c>
      Require all granted

      <LimitExcept GET>
        Require all denied
      </LimitExcept>
    </IfModule>
  </Location>
');
