#!/usr/bin/perl
#use strict;
#use warnings;
use Switch;

my $pid = fork();
exit 0 if $pid != 0;

my $retry_interval = 10;

my $bin = "/opt/interm/bin";
my $conf = "/opt/interm/conf";

my $xml_util = "$bin/xml_util";
my $aoe_conn_xml_file = "aoe_conn.xml";

my $cli_enable_path = "/config/enable";
my $cli_type_path = "/config/cast_type";
my $cli_ip_path = "/config/ip_addr";
my $cli_port_path = "/config/port";
my $cli_file = "128_48000.mp3";
my $cli_mcast_ip_path = "/config/mcast_addr";
my $cli_mcast_port_path = "/config/mcast_port";
my $cli_buf_size_path = "/config/buf_size";
my $cli_buf_rate_path = "/config/buffer_rate";
my $cli_chunk_size_path = "/config/chunk_size";

my $cli_mode;
my $cli_mcast_ip;
my $cli_mcast_port;
my $cli_enable;
my $cli_type;
my $cli_ip;
my $cli_port;
my $fh_pcmconf;
my $pcm_cli_conf = "/tmp/pcm_client.conf";
my $sampling_rate;
my $cli_buf_size;
my $cli_buf_rate;
my $cli_chunk_size;

$cli_enable=`$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_enable_path`;
exit 1 if $? != 0;
$cli_type=`$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_type_path`;
exit 1 if $? != 0;
$cli_mcast_ip=`$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_mcast_ip_path`;
exit 1 if $? != 0;
$cli_mcast_port=`$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_mcast_port_path`;
exit 1 if $? != 0;
$cli_ip=`$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_ip_path`;
exit 1 if $? != 0;
$cli_port=`$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_port_path`;
exit 1 if $? != 0;
$cli_buf_size = `$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_buf_size_path`;
exit 1 if $? != 0;
$cli_buf_rate = `$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_buf_rate_path`;
exit 1 if $? != 0;
$cli_chunk_size = `$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_chunk_size_path`;
exit 1 if $? != 0;

my $oper_xml_file = "oper_mode.xml";
my $oper_mode_path = "/config/type";
my $oper_mode;

$oper_mode=`$xml_util -r -f $conf/$oper_xml_file -t $oper_mode_path`;
exit 1 if $? != 0;

qx|su -c "rm -rf $pcm_cli_conf"|;
open($fh_pcmconf, ">", $pcm_cli_conf) || die "can't open $pcm_cli_conf";
print $fh_pcmconf <<endoftext;

[CLIENT]
DEVICE_NAME		= default
HOST_NAME		= pmu_n
SERVER_IPADDR	= $cli_ip
SERVER_PORT		= $cli_port
RETRY_COUNT		= 3
RATE			= 0
CHANNELS		= 2
MBYTE_SCALE		= $cli_buf_size		// Mega byte
BUFFER_RATE		= $cli_buf_rate		// rate(%)
CHUNK_SIZE		= $cli_chunk_size
MCAST_IPADDR    = $cli_mcast_ip
MCAST_PORT      = $cli_mcast_port
endoftext

while($oper_mode eq "aoe" && $cli_enable eq "yes") {
	switch($cli_type) {
		case "unicast" {
			qx|su -c "$bin/alsa_client -f $pcm_cli_conf"|;
		}
		case "multicast" {
			qx|su -c "$bin/alsa_client -f $pcm_cli_conf -m"|;
		}
	}
		
	sleep $retry_interval;

	$cli_enable=`$xml_util -r -f $conf/$aoe_conn_xml_file -t $cli_enable_path`;
	exit 1 if $? != 0;
}

exit 0;
