#! /bin/perl
if( @ARGV[0] eq "")
{
	print "Usage:perl 17ce_install.pl <user name>\n";
	exit 0;
}

$count=`uname -a | grep  x86_64  | wc -l`;
if($count > 0)
{
	print "64bit system install\n";
	chomp(@ARGV[0]);
	chomp(@ARGV[1]);

	install_libs();
	install();

	sleep 1;
	$count=` ps auxf |  grep -v grep |grep  -c 17ce_node `;

	if($count==0)
	{
		print "install fail\n";
	}
	else
	{
		print "install success\n";

	}
}
else
{
	print "Do not support 32bit system\n";
	exit 0;
}

sub install_libs()
{
        `mkdir -p /usr/local/lib/Poco`;
        chdir('/usr/local/lib/Poco');
        `wget -O /usr/local/lib/Poco/poco_lib.tgz    src.17ce.com/soft/poco_lib.tgz`;
        `tar -zxvf /usr/local/lib/Poco/poco_lib.tgz -C /usr/local/lib/Poco`;

        `mkdir -p /usr/lib`;
        `wget -O  /usr/lib/ice_lib.tgz   src.17ce.com/soft/ice_lib.tgz`;
        `tar -zxvf  /usr/lib/ice_lib.tgz -C /usr/lib`;

        `rm -rf /lib64/libIce.so.32`;
        `ln -s /usr/lib/libIce.so.3.2.1  /lib64/libIce.so.32`;
        `rm -rf /lib64/libIceUtil.so.32`;
        `ln -s /usr/lib/libIceUtil.so.3.2.1  /lib64/libIceUtil.so.32`;
	
	`sysctl net.ipv4.tcp_timestamps=0`;
	`echo net.ipv4.tcp_timestamps=0 >> /etc/sysctl.conf`;
}

sub  install()
{
	`mkdir -p /usr/local/17ce`;
	chdir('/usr/local/17ce');
	`wget /usr/local/17ce/17ce_client.tgz  src.17ce.com/soft/17ce_client.tgz`;
	`tar -zxf 17ce_client.tgz`;
	`rm 17ce_*.tgz*`;
	`rm -rf  /usr/local/17ce/cdn_sys.*`;
	if( not_found_lib() >0)
	{
		print  "17ce_node  not  install \n";
		exit;
	}
	modify_config();
}

sub  modify_config()
{

	$pid=`ps auxf | grep 17ce_node| grep -v grep | awk '{print \$2}' `;
	if($pid)
	{
		print $pid."\n";
		`kill -9  $pid `;
	}

	`sed -i '/LogUser/'d   /usr/local/17ce/17ce_sys.conf`;
	`sed -i '/\\/config/'d   /usr/local/17ce/17ce_sys.conf`;
	`echo '<LogUser>@ARGV[0]</LogUser>'  >>  /usr/local/17ce/17ce_sys.conf`;
	`echo '</config>'  >>  /usr/local/17ce/17ce_sys.conf`;
	#`cat /usr/local/17ce/17ce_restart.pl  | sed  -i '1,\$s/8.8.8.8/@ARGV[1]/'  /usr/local/17ce/17ce_restart.pl`;
	#`cat /usr/local/17ce/config.server  | sed  -i '1,\$s/8.8.8.8/@ARGV[1]/'  /usr/local/17ce/config.server`;

	$count=`grep -c  '/usr/local/17ce/17ce_restart.pl'   /etc/crontab`;
	if($count == 0)
	{
		`echo "* * * * * root  perl  /usr/local/17ce/17ce_restart.pl " >>/etc/crontab`;
		`/etc/init.d/cron* reload`;
	}

	$count=`grep -c  '/usr/local/17ce/17ce_sys.log'   /etc/crontab`;
	if($count ==  0)
	{
		`echo "30  */5  * * * root echo > /usr/local/17ce/17ce_sys.log" >>/etc/crontab`;
		`/etc/init.d/cron* reload`;
	}

	`/usr/local/17ce/17ce_node  --daemon --noclose   --Ice.Config=/usr/local/17ce/config.server  > /dev/null  `;
}

sub not_found_lib()
{
	@str_ist=`ldd  /usr/local/17ce/17ce_node | grep 'not found' |  awk '{print \$1}'`;

	$size= @str_ist;
	if($size)
	{
		print "17ce_node not found lib\n";
	}

	foreach $str (@str_ist)
	{
		chomp($str);
		print $str,"\n";
	}

	return $size;
}

