#!/usr/bin/php
<?php

/**
 * Move conference recording file to appropriate place and add CDR record
 * recording file format example:
 * /var/spool/asterisk/monitor/confbridge-<conference number>-<start timestamp>.wav
 */
require_once('/usr/share/ombutel/www/includes/cli.php');

use ombutel\db;
use ombutel\timezone;
use ombutel\settings;
use ombutel\utils;

if($argc < 4) {
	die("$argv[0]: Invalid script use: conference, filepath, uniqueid\n");
}

list(, $conference, $filepath, $uniqueid) = $argv;
if (file_exists($filepath)) {
	$ts = intval($uniqueid);
	$start_time = (new DateTime("@{$ts}", new \DateTimeZone('UTC')));

	$date_path = $start_time->format('Y/m/d');
	$new_path = "/var/spool/asterisk/monitor/{$date_path}/{$uniqueid}.wav";

	$duration = intval(utils::get_duration($filepath));
	$calltype = 5; //= conference
	$clid = "\"conference\" <$conference>";
	db::begin_transaction();
	if(rename($filepath, $new_path)) { // move and rename recording file
		//add row in cdr
		db::query("insert into `asterisk`.`cdr` (
			`calldate`,
			`clid`,
			`calltype`,
			`source`,
			`src`,
			`destination`,
			`dst`,
			`disposition`,
			`uniqueid`,
			`duration`,
			`billsec`,
			`recfile`
			) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
				$start_time->format('Y-m-d H:i:s'),
				$clid,
				$calltype,
				$conference,
				$conference,
				$conference,
				$conference,
				'ANSWERED',
				$uniqueid,
				$duration,
				$duration,
				$new_path
		);
	}
	db::commit();

	$recording_script = settings::get('call_recording', 'recording_script');
	$timezone = timezone::server()->identifier;
	$start_time = (new DateTime("@{$ts}", new \DateTimeZone('UTC')))
		->setTimezone(new \DateTimeZone($timezone));

	if ($recording_script != null) {
		$search_array = [
			'{MIXMONITOR_FILENAME}',
			'{CDR(start)}',
			'{CDR(calltype)}',
			'{CDR(source)}',
			'{CDR(destination)}',
			'{CDR(uniqueid)}'
		];
		$replace_array = [
			$new_path,
			$start_time->format('Y-m-d H:i:s'),
			$calltype,
			$conference,
			$conference,
			$uniqueid
		];

		$recording = str_replace($search_array, $replace_array, $recording_script); //substitute script arguments
		$result = preg_replace('/\^([^{])/', '\1', $recording); // remove carats of substituted
		exec($result);
	}
}

?>
