#!/usr/bin/php
<?php
/*
  vim: set expandtab tabstop=4 softtabstop=4 shiftwidth=4:
  Codificación: UTF-8
  +----------------------------------------------------------------------+
  | Elastix version 2.0                                                  |
  | http://www.elastix.org                                               |
  +----------------------------------------------------------------------+
  | Copyright (c) 2006 Palosanto Solutions S. A.                         |
  +----------------------------------------------------------------------+
  | Cdla. Nueva Kennedy Calle E 222 y 9na. Este                          |
  | Telfs. 2283-268, 2294-440, 2284-356                                  |
  | Guayaquil - Ecuador                                                  |
  | http://www.palosanto.com                                             |
  +----------------------------------------------------------------------+
  | The contents of this file are subject to the General Public License  |
  | (GPL) Version 2 (the "License"); you may not use this file except in |
  | compliance with the License. You may obtain a copy of the License at |
  | http://www.opensource.org/licenses/gpl-license.php                   |
  |                                                                      |
  | Software distributed under the License is distributed on an "AS IS"  |
  | basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See  |
  | the License for the specific language governing rights and           |
  | limitations under the License.                                       |
  +----------------------------------------------------------------------+
  | The Original Code is: Elastix Open Source.                           |
  | The Initial Developer of the Original Code is PaloSanto Solutions    |
  +----------------------------------------------------------------------+
  $Id: dateconfig.php,v 1.1 2007/01/09 23:49:36 alex Exp $
*/
require_once 'Console/Getopt.php';

// Parse command-line options
$opt = Console_Getopt::getopt($argv, '', array(
    // Date configuration options
    'timezone=',        // New timezone
    'datetime=',        // New date/time
));
if (PEAR::isError($opt)) error_exit($opt->getMessage()."\n");
validateOptions($opt);

exit(action_dateConfiguration($opt) ? 0 : 1);

function error_exit($sMsg, $errorcode = 1)
{
    fwrite(STDERR, $sMsg);
    exit($errorcode);
}

// Parse and validate known command-line options
function validateOptions($opt)
{
    foreach ($opt[0] as $option) switch ($option[0]) {
    case '--timezone':
        if (!preg_match('|^[[:alnum:]-_/]+$|', $option[1]))
            error_exit('Option '.$option[0].": Invalid timezone\n");
        
        // Check on /usr/share/zoneinfo/zone.tab whether the zone exists
        $hArchivo = fopen('/usr/share/zoneinfo/zone.tab', 'r');
        if (!$hArchivo) error_exit('Option '.$option[0].": unable to check timezone\n");
        $bZoneExists = FALSE;
        while (!$bZoneExists && $tupla = fgetcsv($hArchivo, 2048, "\t")) {
            if (count($tupla) >= 3 && $tupla[0]{0} != '#' && $tupla[2] == $option[1]) {
                $bZoneExists = TRUE;
            }
        }
        fclose($hArchivo);
        if (!$bZoneExists) error_exit('Option '.$option[0].": Timezone not found\n");
        
        // Check whether timezone file exists
        if (!file_exists('/usr/share/zoneinfo/'.$option[1]))
            error_exit('Option '.$option[0].": Timezone not found\n");
        break;
    case '--datetime':
        if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $option[1]))
            error_exit('Option '.$option[0].": Invalid datetime\n");
        break;
    }
}

function action_dateConfiguration($opt)
{
    $bExito = TRUE;

	$sDatetime = $sTimezone = NULL;
    foreach ($opt[0] as $option) switch ($option[0]) {
    case '--timezone':
        $sTimezone = $option[1];
        break;
    case '--datetime':
        $sDatetime = $option[1];
        break;
    }

    if (!is_null($sTimezone)) {
    	// Original content de /etc/sysconfig/clock
        $sTimezoneAnterior = 'America/New_York';
        $contenidoClock = array();
        foreach (file('/etc/sysconfig/clock') as $s) {
            $regs = NULL;
        	if (preg_match('/^ZONE\s*=\s*"(.+)"/', $s, $regs)) {
        		$sTimezoneAnterior = $regs[1];
        	} else $contenidoClock[] = $s;
        }
        $contenidoClock[] = "ZONE=\"$sTimezone\"\n";
        
        if ($sTimezone != $sTimezoneAnterior) {
            $sZonefile = '/usr/share/zoneinfo/'.$sTimezone;
            
            // Update /etc/localtime
            if ($bExito && !copy($sZonefile, '/etc/localtime')) {
            	$bExito = FALSE;
                fwrite(STDERR, "ERR: failed update to /etc/localtime\n");
            }
            
            // Update /var/spool/postfix/etc/localtime if present
            if ($bExito && file_exists('/var/spool/postfix/etc/localtime') 
                && !copy($sZonefile, '/var/spool/postfix/etc/localtime')) {
                $bExito = FALSE;    	
                fwrite(STDERR, "ERR: failed update to /var/spool/postfix/etc/localtime\n");
            }
            
            // Update /etc/sysconfig/clock            
            if ($bExito) file_put_contents('/etc/sysconfig/clock', $contenidoClock);
            
            // TODO: /etc/dhcpd.conf contains reference to current timezone
        }
    }

    if (!is_null($sDatetime)) {
    	$output = $ret = NULL;
        exec("/bin/date -s '$sDatetime'");
        if ($ret != 0) $bExito = FALSE;
    }

    return $bExito;
}
?>