#
# $Id$
#
# simple proxy script for forwarding to voicemail server
# for unavailable users
#

loadmodule "modules/sl/sl.so"
loadmodule "modules/tm/tm.so"
loadmodule "modules/rr/rr.so"
loadmodule "modules/maxfwd/maxfwd.so"
loadmodule "modules/mysql/mysql.so"
loadmodule "modules/group/group.so"
loadmodule "modules/usrloc/usrloc.so"
loadmodule "modules/registrar/registrar.so"

# time to give up on ringing -- global timer, applies to 
#    all transactions
modparam("tm", "fr_inv_timer", 90)

# database with user group membership
modparam("group", "db_url", "mysql://ser:heslo@localhost/ser")


# ---------------------  request routing logic -------------------
route {

	if (!mf_process_maxfwd_header("10")) {
		log("LOG: Too many hops\n");
		sl_send_reply("483", "Alas Too Many Hops");
		break;
	};

	if (!(method=="REGISTER")) record_route();
	if (loose_route()) {
		t_relay();
		break;
	};

	if (!uri==myself) {
		t_relay();
		break;
	};

	if (method == "REGISTER") {
		if (!save("location")) {
			sl_reply_error();
		};
		break;
	};

	# does the user wish redirection on no availability? (i.e., is he
	# in the voicemail group?) -- determine it now and store it in
	# flag 4, before we rewrite the flag using UsrLoc
	if (is_user_in("Request-URI", "voicemail")) {
		setflag(4);
	};

	# native SIP destinations are handled using our USRLOC DB
	if (!lookup("location")) {
		# handle user which was not found
		route(4);
		break;
	};

	# if user is on-line and is in voicemail group, enable redirection
	if (method == "INVITE" && isflagset(4)) {
		t_on_failure("1");
	};
	t_relay();
}

# ------------- handling of unavailable user ------------------
route[4] {

	# non-Voip -- just send "off-line"
	if (!(method == "INVITE" || method == "ACK" || method == "CANCEL")) {
		sl_send_reply("404", "Not Found");
		break;
	};

	# not voicemail subscriber
	if (!isflagset(4)) { 
		sl_send_reply("404", "Not Found and no voicemail turned on");
		break;
	};

	# forward to voicemail now
	rewritehostport("bat.iptel.org:5090");
	t_relay_to_udp("bat.iptel.org", "5090");	
}

# if forwarding downstream did not succeed, try voicemail running
# at bat.iptel.org:5090

failure_route[1] {
	revert_uri();
	rewritehostport("bat.iptel.org:5090");
	append_branch();
	t_relay_to_udp("bat.iptel.org", "5090");
}
