#!/usr/bin/php
<?php

# Works similar to how cloudrec-upload does

$call = (object) [
	"file" => "",
	"time" => "",
	"type" => "",
	"src" => "",
	"source" => "",
	"dst" => "",
	"destination" => "",
	"uniqueid" => "",
	"id" => "",
];

try {
	parse_cmdline($argv, $call);
	// ignore empty files
	if (filesize($call->file) <= 44) { // WAV header size is 44
		@unlink($call->file);
		return;
	}
	create_symlink($call);
} catch (Exception $e) {
	log_to_logfile($call, $e->getMessage());
	log_to_syslog($call, $e->getMessage());
}

function log_to_logfile($call, $msg) {
	file_put_contents(
		"/var/log/cpbx/recording-upload.log",
		"{$msg} ({$call->file})\n",
		FILE_APPEND);
}

function log_to_syslog($call, $msg) {
	openlog("upload-recording", LOG_PID, LOG_LOCAL1);
	syslog(LOG_WARNING, "{$msg} ({$call->file})\n");
	closelog();
}

function parse_cmdline($argv, &$call) {
	foreach (array_slice($argv, 1) as $arg) {
		list($name, $val) = explode("=", $arg, 2);
		$call->$name = $val;
		if ($name == "del") {
			$call->del = $val == "y";
		} else if ($name == "id") {
			$call->uniqueid = $val;
		}
	}
	foreach (["file", "time", "type", "uniqueid"] as $key) {
		if ($call->$key == "") {
			throw new Exception("Missing command-line argument: $key=");
		}
	}
	# Remove potentially harmful charachters: Those are not likely
	# to be present. If they will, they may cause odd results:
	foreach (['time', 'src', 'dst', 'source', 'destination'] as $key) {
		preg_replace('_[\\{}<>~$;&|*?#`"\'/]+_', '', $call->$key);
	}
	# 'file': Allow '/'
	preg_replace('_[\\{}<>~$;&|*?#`"\']+_', '', $call->file);
	preg_replace('_[^\d.]+_', '', $call->uniqueid);
	preg_replace('_[^\d]+_', '', $call->type);

	if ($call->dst == 's') {
		$call->dst = '';
	}

	if (!file_exists($call->file)) {
		throw new Exception("Original recording does not exist ({$call->file})");
	}
	$call->id = $call->uniqueid;
}

function create_symlink($call) {
	switch ($call->type) {
		case 1:
			$direction = "INTERNAL";
			break;
		case 2:
			$direction = "INCOMING";
			break;
		case 3:
			$direction = "OUTGOING";
			break;
		case 5:
			$direction = "CONFERENCE";
			break;
		default:
			$direction = "APPLICATION";
	}
	$caller = coalesce($call->src, $call->source, "0000");
	$called = coalesce($call->dst, $call->destination, "0000");
	$datetime = format_date($call->time);
	// TODO: allow customization
	$parts = implode("_", [ $direction, $caller, $called, $datetime, $call->id ]);
	$ext = pathinfo($call->file, PATHINFO_EXTENSION);
	$link = "/var/spool/asterisk/cpbx-upload-rec/{$parts}.{$ext}";
	@mkdir(dirname($link), 0775, true);
	@symlink($call->file, $link);

	// Check for corresponding transcription file
	$json_file = str_replace('.wav', '.json', $call->file);
	if (file_exists($json_file)) {
		$json_link = "/var/spool/asterisk/cpbx-upload-rec/{$parts}.json";
		@mkdir(dirname($json_link), 0775, true);
		@symlink($json_file, $json_link);
	}
}

function format_date($full_time) {
	list($date, $time) = explode(' ', $full_time, 2);
	return "${date}T${time}";
}

function coalesce() {
	// PHP 5.4 doesn't support variadic functions
	foreach (func_get_args() as $arg) {
		if ($arg != '') {
			return $arg;
		}
	}
}

?>
