#!/usr/bin/php
<?php

/* This crontab adds/remove FPM pools for any php fpm version
   for each user who uses a fpm configuration
*/

require_once("/usr/share/alternc/panel/class/config_nochk.php");

// first launch sync_unix since we NEED unix user to exist!
passthru("/usr/lib/alternc/install.d/alternc-nss end");

$force = (isset($argv[1]) && $argv[1]=="force");

$login_prefix = variable_get('nss_login_prefix', '', 'If not empty, override prefix set in local.sh with LOGIN_PREFIX');
if (empty($login_prefix)) {
    $login_prefix = !empty($GLOBALS['L_LOGIN_PREFIX']) ? $GLOBALS['L_LOGIN_PREFIX'] . "_" : "";
}

$db->query("SELECT DISTINCT CONCAT('".$login_prefix."',m.login) as login,m.uid,sd.type FROM sub_domaines sd, membres m WHERE m.uid=sd.compte AND sd.type LIKE 'php__-fpm';");

$reload=array();
$allpools=array();
$allversions=array();

foreach(glob("/usr/lib/tmpfiles.d/php*-fpm.conf") as $path) {
    $allversions[]=preg_filter('/(.*)([0-9]+\.[0-9]+)(.*)/',"$2",$path);
}

// detect installed fpm versions
foreach($allversions as $k=>$version) {
    if (!is_dir("/etc/php/$version/fpm/pool.d")) {
        unset($allversions[$k]);
    }
}


function myecho($str) {
	 static $first=true;
	 if ($first) {
	    echo date("Y-m-d H:i:s")." Log of php7-fpm\n";
	    $first=false;
	 }
	 echo $str."\n";
}

while ($db->next_record()) {
      $version=substr($db->f("type"),3,1).".".substr($db->f("type"),4,1);
      $user=$db->f("login");
      $allpools[$version][]=$user;
      if ($force || !is_file("/etc/php/".$version."/fpm/pool.d/".$user.".alternc.conf")) {
          myecho("Creating php $version fpm pool for user $user");
          file_put_contents("/etc/php/".$version."/fpm/pool.d/".$user.".alternc.conf",
            str_replace(
              array("%%LOGIN%%","%%PHPVERSION%%"),
              array($user,$version),
              file_get_contents("/etc/alternc/templates/php/fpm")
            )
          );
          $reload[$version]=$version;
      }
}

// now delete pools we don't need anymore
foreach($allversions as $version) {
    $d=opendir("/etc/php/$version/fpm/pool.d");
    while (($c=readdir($d))!==false) {
        if (preg_match('#([^\.]*).alternc.conf$#',$c,$mat)) {
            $user=$mat[1];
            if (empty($allpools[$version]) || !in_array($user,$allpools[$version])) {
                myecho("Deleting php $version fpm pool for user $user");
                @unlink("/etc/php/".$version."/fpm/pool.d/".$user.".alternc.conf");
                $reload[$version]=$version;
            }
        }
    }
}

// now reloads php fpm versions
foreach($reload as $service) {
    if (file_exists("/etc/init.d/php".$service."-fpm")) {
        passthru("/etc/init.d/php".$service."-fpm reload");
    }
}

