<?php

$ftp_server = "172.16.0.155";
$ftp_user_name = "anonymous";
$ftp_user_pass = "";
$errorMsg = "";

if ($action == ""):
  $errorMsg = "parameter missing";
else:
  $ftpId = ftp_connect("$ftp_server");
  if ($ftpId):
    if (!ftp_login($ftpId, $ftp_user_name, $ftp_user_pass)):
      $errorMsg = "could not connect to $ftp_server";
    endif;
  else:
    $errorMsg = "could not login on $ftp_server";
  endif;  

  if ($errorMsg == ""):  
    if ($action == "down"):
      if (ftp_chdir($ftpId, "download")):
        do {
          $edi_files = ftp_nlist($ftpId, ".");
          if (in_array("edi_ftp.lock.txt", $edi_files)):
            writeLogFtp("waiting for another running edi_ftp-download to terminate...");
            sleep(1);
          endif;
        } while (in_array("edi_ftp.lock.txt", $edi_files));
      	  writeLogFtp("uploading 'edi_ftp.lock.txt' to $ftp_server");
     	  if (!ftp_put($ftpId, "./" . "edi_ftp.lock.txt", "edi_ftp.lock.txt", FTP_BINARY)):
          $errorMsg = "could not upload 'edi_ftp.lock.txt'";
        endif;
        foreach ($edi_files AS $edi_file) {
        	if ($edi_file != "edi_ftp.lock.txt"):
          	writeLogFtp("downloading $edi_file from $ftp_server");
         	  if (!ftp_get($ftpId, "../temp/edifact/" . $edi_file, $edi_file, FTP_BINARY)):
              $errorMsg = "could not download $edi_file";
              break;
            endif;
       	    writeLogFtp("deleting $edi_file from $ftp_server");
            if (!ftp_delete($ftpId, $edi_file)):
              $errorMsg = "could not delete $edi_file";
              break;
            endif;
            break;
          endif;
        }        
       	writeLogFtp("deleting 'edi_ftp.lock.txt' from $ftp_server");
        if (!ftp_delete($ftpId, "edi_ftp.lock.txt")):
          $errorMsg = "could not delete 'edi_ftp.lock.txt'";
        endif;
      else:
        $errorMsg = "could not change to dir 'download'";
      endif;
    elseif ($action == "up"):
      if (ftp_chdir($ftpId, "upload")):
        foreach ($edi_files AS $edi_file) {
        	writeLogFtp("uploading $edi_file to $ftp_server");
       	  if (!ftp_put($ftpId, $edi_file, "../temp/edifact/" . $edi_file, FTP_BINARY)):
            $errorMsg = "could not upload $edi_file";
            break;
          endif;
        }
      else:
        $errorMsg = "could not change to dir 'upload'";
      endif;
    else:
      $errorMsg = "invalid parameter: $action";
    endif;
  endif;
  
  ftp_quit($ftpId);
endif;

if ($errorMsg != "")
  writeLogFtp($errorMsg);

function writeLogFtp($log_text)
{
  $today = getdate();
  $fileHandle = @fopen("../log/amazon_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
  @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [edi_ftp.inc.php] " . $log_text .  "\n");
  @fclose($fileHandle);
  return;
}

?>