#!/usr/bin/php
<?php

### functions


########################################################################

/// init
	global $ini;
	global $node;

	require(dirname(__FILE__)."/../include/functions.php");
	check_force_run(1);
	init();

	if (get_ini_opt('confgen','opendkim-confgen') === '0') { exit(0); }

	check_update('opendkim_update');

### includes
	require(dirname(__FILE__)."/../include/template.class.php");

### read configuration options

	if (!(array_key_exists('opendkim', $ini) && array_key_exists('confdir', $ini['opendkim']) && file_exists($ini['opendkim']['confdir'])))
	{
		panic("Opendkim confdir not defined!");
	}

	if (!(array_key_exists('active_key', $ini['opendkim']) && $ini['opendkim']['active_key']!=""))
	{
		panic("Opendkim active key id not defined!");
	}

#	if (!(array_key_exists('key', $ini['opendkim']) && array_key_exists($ini['opendkim']['active_key'], $ini['opendkim']['key'])))
#	{
#		panic("Opendkim public key not configured: ".$active_key_id);
#	}

	if (!(array_key_exists('name', $ini['opendkim']) && $ini['opendkim']['name']!=""))
	{
		panic("Opendkim daemon name not defined!");
	}

### generate dkim selector: default_host-active_key._domainkey

	if (is_numeric($ini['opendkim']['active_key']))
	{
		// compatibility
		$dkim_selector=$ini['global']['host'].'-'.str_pad($ini['opendkim']['active_key'], 2, '0', STR_PAD_LEFT);
	}
	else
	{
		// custom selector
		$dkim_selector=$ini['opendkim']['active_key'];
	}

### check if private key file exists

#	if (!(file_exists($ini['opendkim']['confdir']."/keys/".$dkim_selector."private")))
#	{
#		panic("Opendkim private key file not found: ".$dkim_selector."private");
#	}

### Delete last backup of opendkim tables

	if (file_exists($ini['opendkim']['confdir'].'/KeyTable.bck'))
	{
		unlink($ini['opendkim']['confdir'].'/KeyTable.bck'); 
	}

	if (file_exists($ini['opendkim']['confdir'].'/KeyTable'))
	{
		rename($ini['opendkim']['confdir'].'/KeyTable',$ini['opendkim']['confdir'].'/KeyTable.bck');
	}

	if (file_exists($ini['opendkim']['confdir'].'/SigningTable.bck'))
	{
		unlink($ini['opendkim']['confdir'].'/SigningTable.bck'); 
	}

	if (file_exists($ini['opendkim']['confdir'].'/SigningTable'))
	{
		rename($ini['opendkim']['confdir'].'/SigningTable',$ini['opendkim']['confdir'].'/SigningTable.bck');
	}

### collect domain data

	logme("opendkim: Export started");
	
	$sql="SELECT `domain`.`name` AS hostname,
			`domain`.`name` AS domain
		FROM `domain`
		LEFT JOIN `client` ON `domain`.`clientid`=`client`.`id`
		WHERE (
			(`domain`.`dns`=1 OR `domain`.`dkim`=1)
			AND `domain`.`active`=1
			AND `client`.`active`=1
			)
			OR `domain`.`name` = '".$ini['global']['domain']."'
		UNION
		SELECT CONCAT(`dom_host`.`host`, '.', `domain`.`name`) AS hostname,
			`domain`.`name` AS domain
		FROM `dom_host`
		LEFT JOIN `domain` ON `dom_host`.`domainid`=`domain`.`id`
		LEFT JOIN `client` ON `domain`.`clientid`=`client`.`id`
		WHERE
			`dom_host`.`active`=1
			AND `domain`.`active`=1
			AND `client`.`active`=1
			AND `dom_host`.`host` NOT LIKE '%*%'
			AND ( `domain`.`dns`=1 OR `dom_host`.`dkim`=1 )
		;";

#			AND (`dom_host`.`mx` IS NULL OR `dom_host`.`mx`!='')
#			AND (`client`.`node`=".$node." OR `client`.`migrate`=1)
#			AND (`client`.`node`=".$node." OR `client`.`migrate`=1)


	$res=DBquery($sql) or die(1);
	$n=$res->num_rows;

	logme ("opendkim: Configuring key and signing tables for $n hostnames");

### generate Opendkim KeyTable and SigningTable

	$template = new Template;
	$template->template_dir = $ini['global']['template_dir'];
	$template->compile_dir = $ini['global']['template_dir']."_c";

	$template->assign_md_array($res, 'hosts');

	$template->assign('def_domain',$ini['global']['domain']);
	$template->assign('def_host',$ini['global']['host']);
	$template->assign('dkim_selector',$dkim_selector);

### save opendkim KeyTable and SigningTable

	fpush($ini['opendkim']['confdir'].'/KeyTable',$template->fetch('opendkim_key.tpl'));
	fpush($ini['opendkim']['confdir'].'/SigningTable',$template->fetch('opendkim_signing.tpl'));


### Check configs

# no configtest yet
#	if (exec_err($ini['opendkim']['conftest'].' 2>/dev/null') != 0)
#	{
#		panic("Opendkim config error");
#	}

### reload OpenDKIM

	daemons_startstop(array($ini['opendkim']['name'] => 'reload'));

### reset update flag

	unlock_update('opendkim_update');

	logme("opendkim: Export done.");
