debug=3
memdbg=6
memlog=6
loadmodule "sl"
loadmodule "tm"
loadmodule "tmx"
loadmodule "xlog"
loadmodule "maxfwd"
loadmodule "pv"
loadmodule "kex"
loadmodule "carrierroute"
loadmodule "mi_fifo"

modparam("mi_fifo", "fifo_name", "/tmp/kamailio_fifo")

route{
	# initial sanity checks
	if (!mf_process_maxfwd_header("10")) {
		sl_send_reply("483", "Too Many Hops");
		return;
	}
	if (msg:len > 4096) {
		sl_send_reply("513", "Message too big");
		return;
	}
	# set flag for later test
	setflag(0);
	resetflag(1);
	setflag(2);

	# user route
	if(cr_user_carrier("$rU", "$rd", "$avp(s:11)")) {
		$avp(s:10)="domain0";
		if (!cr_route("$avp(s:11)", "$avp(s:10)", "$rU", "$rU", "call_id", "$avp(s:13)")) {
			xlog("L_ERR", "cr_route failed\n");
			exit;
		}
		t_on_failure("1");
		$avp(s:12) = $rd+":"+$rp;
		#xlog("host: $avp(s:12), comment: $avp(s:13)");
	} else {
	# default route
		if (!cr_route("default", "domain0", "$rU", "$rU", "call_id")) {
			xlog("L_ERR", "cr_route failed\n");
			exit;
		}
	}
	if (!t_relay()) {
		sl_reply_error();
	}
}

failure_route[1] {
	xlog("entered failure route with result $T_reply_code");
	revert_uri();
	if (!cr_next_domain("$avp(s:11)", "$avp(s:10)", "$rU", "$avp(s:12)", "$T_reply_code", "$avp(s:10)")) {
		xlog("L_ERR", "cr_next_domain failed\n");
		exit;
	}
	if (!cr_route("$avp(s:11)", "$avp(s:10)", "$rU", "$rU", "call_id")) {
		xlog("L_ERR", "cr_route failed\n");
		exit;
	}
	$avp(s:12) = $rd+":"+$rp;
	t_on_failure("1");
	km_append_branch();
	if (!t_relay()) {
		xlog("L_ERR", "t_relay failed\n");
		exit;
	}
}
