#!/usr/bin/php -q
<? /*
	Script to fix broken DB entries. See BR410.
*/

	$monarr = array("Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4, "May" => 5, "Jun" => 6,
                "Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12);

        include_once("../includes/mysql.php");

	$query = "select `id`, `expire` from `domaincerts` where expire='0000-00-00 00:00:00'";
	$res = mysql_query($query);

	while($row = mysql_fetch_assoc($res))
	{
		$row['crt_name'] = "../crt/server-".$row['id'].".crt";

		echo "FROM| ID: " . $row['id'] . ", Expiry: " . $row['expire'] . "\n";

		if(filesize($row['crt_name']) > 0 )
                {
                        $end = trim(`/usr/bin/openssl x509 -in '$row[crt_name]' -noout -enddate`);
                        $bits = explode("=", $end, 2);
                        $end = trim($bits[1]);

                        while(strstr($end, "  "))
                                $end = str_replace("  ", " ", $end);
                        $bits = explode(" ", $end);
                        $month = $bits['0'];
                        $month = $monarr[$month];
                        $day = $bits['1'];
                        $time = $bits['2'];
                        $year = $bits['3'];
                        $bits = explode(":", $time);
                        $hour = $bits['0'];
                        $min = $bits['1'];
                        $sec = $bits['2'];
                        $date = gmmktime($hour, $min, $sec, $month, $day, $year);

                        $cert = trim(`/usr/bin/openssl x509 -in $row[crt_name]`);
                        $bits = explode("=", trim(`/usr/bin/openssl x509 -serial -noout -in '$row[crt_name]'`), 2);
                        $serial = $bits['1'];

                        $query = "update `domaincerts` set `expire`=FROM_UNIXTIME($date) where `id`='".$row['id']."'";
			echo "TO  | ID: " . $row['id'] . ", Expiry: " . $date . "\n";
			echo $query . "\n\n";

                        //mysql_query($query);
		}
	}

