echo 'Checking for $1...'

success=1
while [ $success -ne 0 ]
do
  ping -c 1 $1
  success=$?
  sleep 1
done

echo ""
echo "Target node located, stand by..."
sleep 5

mountpoint -q /home/rover/sed-logs

if [ $? -ne 0 ]
then
  echo ""
  echo "Mounting ses:/media/data/logs on sed-logs..."
  success=1
  sshfs root@134.89.42.124:/media/data/logs /home/rover/sed-logs
  success=$?
  if [ $success -ne 0 ]
  then
    echo "Failed to mount ses:/media/data/logs on sed-logs..."
    exit 1
  fi
  sleep 1
else
  echo "ses:/media/data/logs already mounted on sed-logs..."
  echo "Checking for new plan data on sed-logs..."
fi

# Compare the number of .b16 files on the ses and locally
# If the number on the ses is greter than the number locally
# then update the local log directory
latestmarsdep=`ls /home/rover/sed-logs/ | grep "dep-" | tail -1`
latestheredep=`ls /home/rover/logs/SED/ | grep "dep-" | tail -1`
echo "Latest deps are $latestmarsdep and $latestheredep"
if [ $latestmarsdep == $latestheredep ]
then
  echo ""
  echo "Latest dep folders are equal, check the plan folders..."
else
  echo ""
  echo "Copying latest dep data from ses to local drive..."
  cp -pvru /home/rover/sed-logs/* /home/rover/logs/SED/.
  exit 0
fi

latestmarspln=`ls /home/rover/sed-logs/$latestmarsdep | grep "plan-" | tail -1`
latestherepln=`ls /home/rover/logs/SED/$latestheredep | grep "plan-" | tail -1`
echo "Latest plans are $latestmarspln and $latestherepln"
if [ $latestmarspln == $latestherepln ]
then
  echo ""
  echo "Latest plan folder has been copied - nothing to do"
  exit 0
fi

echo "Two b16 files in the plan folder signal that the sample is complete"
nmarspics=`find /home/rover/sed-logs/$latestmarsdep/$latestmarspln -name *.b16 | wc -l`

if [ $nmarspics == "2" ]
then
  echo ""
  echo "Copying latest plan data from ses to local drive..."
  cp -pvru /home/rover/sed-logs/* /home/rover/logs/SED/.
else
  echo "SES plan not finished..."
fi

exit 0
