<?php
//
// Created on: 11 Sep 2001
// Usage: cfg_upload.php?[language="eng|gb"]
//                        &bssid=0
//                        &version=iw05_01.048
//                        &tarfile=/usr/local/apache/htdocs/bss_db/bss0_20010914_0.tar.gz
// 
// Function: Transfer BSS software from OMC Server
//           to BSC harddisk based on bssdist.fls file
//
//
//
//
// Remarks:
//     - Use explode() as a faster split()
//     - Function like tar, mount, umount return 0 if there is no error
//
?>

<?php
include("nocache.inc");
include("header.inc");
include("ip2name.inc");
include("read_bssdist.inc");
include("cfg_upload.inc");
?>

<?
//$debug=1;

if (!isset($language))
	$language="eng";
$parameter="${language}namearray";


if (!isset($version) || !isset($bssid))
{
	echo "<font color=red size=+1>{${$parameter}["err_msg"]}</font>";
	return;
}
//$url_temp=$_SERVER["REQUEST_URI"];
//echo "This page URL:$url_temp<br>";

/*****************************************
* Locate tar file if it is not given
*
*****************************************/
if (!isset($tarfile))
{
	echo "<HTML>\n";
?>

<script language="JavaScript">
<!--
	function submit_check(myForm)
	{
		if (myForm.selectfile.value == "")
		{
			alert("No filename found");
			return (false);
		}
		myForm.tarfile.value = "/usr/local/apache/htdocs/bss_db/" + myForm.selectfile.value + ".tar.gz";
		return (true);
	}
//-->
</script>

<?php
	echo "<font color=blue size=+1>{${$parameter}["availfile"]}:</font>";
	echo "<HR>\n";

	echo "<PRE>\n";
	if (is_dir("/usr/local/apache/htdocs/bss_db"))
	{
		//$backuplist = Array();
		exec("ls -1t /usr/local/apache/htdocs/bss_db",$backuplist,$retval);
		$backupcount = count($backuplist);
		if ($backupcount <= 0)
			echo "{${$parameter}["no_backup"]}\n";
		else
			system("ls -1lht /usr/local/apache/htdocs/bss_db");
			
	}
	else
	{
		echo "{${$parameter}["no_backup"]}\n";
	}
	echo "</PRE>\n";



	echo "<BR>\n";
	echo "<FORM action=cfg_upload.php method=post onSubmit='return submit_check(this);'>\n";
	echo "<font color=blue size=+1>{${$parameter}["selectfile"]}: </font>";
	echo "<INPUT type=text name=selectfile value=\"bss${bssid}_" . date("Y_m_d_H") . "\">\n";
	echo ".tar.gz";

	echo "<HR>\n";
	echo "<INPUT type=hidden name=language value=$language>\n";
	echo "<INPUT type=hidden name=bssid value=$bssid>\n";
	echo "<INPUT type=hidden name=version value=$version>\n";
	echo "<INPUT type=hidden name=tarfile>\n";

	echo "<INPUT type=submit value={${$parameter}["submit"]} style='width: 80'>\n";
	if (isset($bssid))
		echo "<INPUT type=button value='{${$parameter}[back]}' " .
		"onClick='javascript:parent.location.href=" .
		"\"modifyBssParam.php?language=$language&bssid=$bssid\"'>";
	echo "</FORM>\n";
	echo "</HTML>\n";

	return;
}

/******************************************
* Mount the BSC /hd0 to /tmp/$$ directory
*******************************************/
$tmpdir = sprintf("%.3f",time()/1000);
$iwbox = "bss${bssid}";
$ip = name2ip($iwbox);
$path_prefix = "/tmp";

//-----------------FTP BSC Config,BSS -> EMS ---------------------
$bscLoginName="www";
$bscLoginPassword="123456";
$file_list_name="/tmp/file_list.txt";

flush();
echo "Please wait, the operation will take some time<br>";
ob_flush();
flush();

system("rm -rf $path_prefix/$iwbox");

mkdir("$path_prefix/$iwbox", 0755);

system("./ftpGetList $ip $bscLoginName $bscLoginPassword /hd0/{$version}/compile/cfg $path_prefix/$iwbox 1>/dev/null 2>&1");

$conn_id=ftp_connect($ip);
if($conn_id == FALSE)
{
	echo "<b>FTP:connect to $ip <font color=red>failed</font>.</b><br>";
	back();
}
if(FALSE == ftp_login($conn_id,$bscLoginName,$bscLoginPassword))
{
	echo "<b>FTP:login to $ip <font color=red>failed</font>.</b><br>";
	back();
}

$handle = @fopen($file_list_name, "r");

if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        if(strlen(trim($buffer)) < 8)
        	continue;
        $sp=explode(",",$buffer);
        $remote_dir=trim($sp[0]);
        $local_dir=trim($sp[1]);
        $ftpfile=trim($sp[2]);
        
        
flush();
echo "<img border=\"0\" src=\"../../images/arrow.gif\" width=\"10\" height=\"10\">"; 
ob_flush();
flush();

        
        //ftp_chdir($conn_id,$remote_dir);
        $tmp1=$local_dir."/".$ftpfile;
        $tmp2=$remote_dir."/".$ftpfile;
        //echo "Get {$tmp2} from $iwbox ";
				ftp_get($conn_id,$tmp1,$tmp2,FTP_BINARY);
    }
    fclose($handle);
}
ftp_close($conn_id);

unlink($file_list_name);

flush();
echo "<br>Compress $tarfile<br>"; 
ob_flush();
flush();

chdir("$path_prefix/$iwbox");
system("tar zcf $tarfile .");
system("rm -rf $path_prefix/$iwbox");

echo "Backup $tarfile completely<br>";
back();
exit();
//-----------------FTP BSC Config END---------------------------

/***************************************************************************************
* PHP state machine
*
* Rename original build and create directory
* Format: it is a 2D array
*	Array(
*         Array('function','description','next state if success','next state if fail'
*       )
****************************************************************************************/
$cmdlist = Array(
	's00' => Array ('system("/bin/ping -q -c 1 $ip >> /dev/null", $retval);return($retval);',
		"{${$parameter}["ping"]} $iwbox ($ip) ...",
		"kickout","s01"),

	's01' => Array ('return(is_dir("$path_prefix/$iwbox"));',
		"{${$parameter}["checkexist"]} $path_prefix/$iwbox",
		"s03","s02"),

	's02' => Array ('return(mkdir("$path_prefix/$iwbox",0700));',
		"{${$parameter}["create_dir"]} $path_prefix/$iwbox",
		"s03","halt"),

	's03' => Array ('system("/bin/umount $path_prefix/$iwbox", $retval);return($retval);',
		"",
		//"{${$parameter}["umounting"]} $path_prefix/$iwbox",
		"s04","s03"),

	's04' => Array ('system("/bin/mount -t nfs $ip:/hd0 $path_prefix/$iwbox", $retval);return($retval);',
		"{${$parameter}["mounting"]} -t nfs $ip:/hd0 $path_prefix/$iwbox",
		"s40","halt"),

	's40' => Array ('return(is_dir(sprintf("$path_prefix/$iwbox/%s/compile/cfg",strtoupper($version))));',
		"{${$parameter}["checkexist"]} $path_prefix/$iwbox/$version/compile/cfg",
		"s41","halt"),

	's41' => Array ('return(chdir (sprintf("$path_prefix/$iwbox/%s/compile/cfg",strtoupper($version))));',
		"{${$parameter}["chdir"]} $path_prefix/$iwbox/$version/compile/cfg",
		"s60","halt"),

	's60' => Array ('return(is_file("$tarfile"));',
		"{${$parameter}["checkexist"]} $tarfile",
		"halt","s61"),

	's61' => Array ('system("tar zcf $tarfile .", $retval);return($retval);',
		"{${$parameter}["tar"]} $tarfile ...",
		"halt","cleanup"),

	"cleanup" => Array('return(is_dir("$path_prefix/$iwbox"));',
		"{${$parameter}["checkexist"]} $path_prefix/$iwbox",
		"chroot","getout"),

	'chroot' => Array ('return(chdir("/"));',
		"{${$parameter}["chdir"]} $path_prefix/$iwbox/$version/compile/cfg",
		"umount","getout"),

	"umount" => Array('system("/bin/umount -v $path_prefix/$iwbox", $retval);return($retval);',
		"{${$parameter}["umounting"]} $path_prefix/$iwbox",
		"rmdir","umount"),

	"rmdir" => Array('return(rmdir("$path_prefix/$iwbox"));',
		"{${$parameter}["rmdir"]} $path_prefix/$iwbox",
		"getout","getout")
);


if (isset($debug))
{
	foreach ($cmdlist as $key => $value)
	{
		echo "$key,$value[0],$value[1],$value[2],$value[3]<BR>";
	}
}


/*********************************************
 * Execute the state machine here
 *********************************************/
echo "<font color=red size=+1>{${$parameter}["heading"]}<BR></font>";
echo "<PRE>";
for ($state="s00" ; ; )
{
	if (isset($debug))
		echo "{$cmdlist[$state][0]}\n$state: ";

	echo "{${cmdlist}[$state][1]}";
	flush();
	if (@eval(${cmdlist}["$state"][0]))
		$state = $cmdlist[$state][2];
	else
		$state = $cmdlist[$state][3];


	if ($state == "getout")
	{
		echo " ... {${$parameter}["ok"]}\n";
		break;
	}
	else if ($state == "kickout")
	{
		echo " ... {${$parameter}["not_ok"]}\n";
		echo "</PRE><font color=red size=+1>... {${$parameter}["failed"]}<BR></font>";
		echo "<PRE>";
		break;
	}
	else if ($state == "halt")
	{
		echo " ... {${$parameter}["not_ok"]}\n";
		echo "</PRE><font color=red size=+1>... {${$parameter}["failed"]}<BR></font>";
		echo "<PRE>";
		$state = "cleanup";
	}
	else
	{
		if (${cmdlist}[$state][1] != "")
			echo " ... {${$parameter}["ok"]}\n";
	}
}

echo "</PRE><font color=blue>... {${$parameter}["done"]}<BR></font>";

function back()
{
	global $bssid,$language;
	
	if (isset($bssid))
		echo "<INPUT type=button value='Back' " .
		"onClick='javascript:parent.location.href=" .
		"\"modifyBssParam.php?language=$language&bssid=$bssid\"'>";
}
?>
