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

define(WWW_PATH,'/var/www/html/');
define(USER_DIR,'www');

$is_root = is_writable('/etc/bashrc');

$user = $_SERVER['argv'][1];
if(preg_match('/\W/', $user)) {
  echo "syncweb v.3.0\n(C) Tomi Belan 2005\n";
  echo "Usage: syncweb [user]\n";
  echo "(if you specify an user, only that user will be synced)\n";
  exit;
}

echo " *** SYNCWEB v.3.0\n";

/*
echo " *** copying global web from ~pages/www-new/ ... ";
system('bash -c "cp -f /home/pages/www-new/* '.WWW_PATH.'"');
echo "done\n";
*/

/*
echo " *** creating /var/www/html/passwd.php from /etc/passwd ... "
$file = fopen('/var/www/html/passwd.php', 'w');
fwrite($file, '<?'+'php /'+"*\n");
fwrite($file, implode('', file('/etc/passwd')));
fwrite($file, '*'+'/ ?'+">\n");
*/

$file = file('/etc/passwd');
foreach($file as $line) {
  $z = explode(':', $line);
  $name     = $z[0];
  $uid      = $z[2];
  $gid      = $z[3];
  $fullname = $z[4];
  $homedir  = $z[5];
  
  // system users can't have homepage
  if($uid < 500)
    continue;
  
  // if we've specified an user, don't care about the others
  if(!empty($user) && $name != $user)
    continue;
  
  // ignore what we don't own
  if(!is_writable($homedir))
    continue;
  
  // if the user doesn't have a homepage
  if(!is_dir($homedir.'/'.USER_DIR)) {
    if(is_dir(WWW_PATH.$name) && $is_root)
      system('rm -rf '.WWW_PATH.$name);
    continue;
  }
  
  // print info if there's not a WWW_PATH.$name yet
  if(!$is_root && !file_exists(WWW_PATH.$name)) {
    echo " *** WARNING:\n";
    echo " *** Your web directory '".WWW_PATH.$name."' is not created yet.\n";
    echo " *** You don't have the permission to create it, but\n";
    echo " *** it will be created automatically next midnight.\n";
    echo " *** Then, you will be able to modify it.\n";
    continue;
  }
  
  // one more check
  if(!is_writable(WWW_PATH.$name))
    continue;
  
  // copy the files
  if(!is_dir(WWW_PATH.$name))
    mkdir(WWW_PATH.$name);
  echo " *** copying $name\t$fullname\n";
  system('chown '.$name.':'.$gid.' '.WWW_PATH.$name);
  system('mirrordir '.$homedir.'/'.USER_DIR.' '.WWW_PATH.$name);
  system('find '.WWW_PATH.$name.' -type f -exec chmod 644 {} \;');
}

echo " *** syncweb ending\n"

?>