#!/bin/sh

# Check if script is executed as part of buildroot build system
if [ ! -z `pwd | grep buildroot` ]; then
  BRINITD="output/target/etc/init.d"
  INITSCRIPT="S70clone"
  if [ ! -d $BRINITD ]; then
    echo "ERROR: Cannot find $BRINITD"
    exit 1
  fi
  echo "### Copying $0 to $BRINITD/$INITSCRIPT ..."
  cp $0 $BRINITD/$INITSCRIPT
  rm $BRINITD/S40network  # Do not try to start network
  exit 0  # Buildroot modification done; leave script
fi

# Executed on the device from here on

if [ "$1" = "stop" ]; then
  exit 0  # There is nothing to stop
fi

SCB=/sys/class/block

echo -e "\033[1;35m  Waiting for USB block devices ...\033[0m"
i=0
while [ 1 ]; do
  if [ ! -z "`ls -l $SCB | grep usb`" ]; then  # Any USB block devices present?
    break
  else
    i=$(($i+1))
    if [ $i -gt 5 ]; then
      break
    fi
    sleep 1
  fi
done

if [ -z "`ls -l $SCB | grep usb`" ]; then
  echo -e "\033[1;35m  Cannot find USB drive!\033[0m"
  exit 1
fi

FOUND=0
BINDIR=VIPAclone
TMPDIR=/tmp
SCRIPT=VIPAclone.sh

for BDEV in `ls $SCB`  # Step through all block devices
do
  if [ -f $SCB/$BDEV/start ]; then  # Only partitions
  if [ ! -z "`readlink $SCB/$BDEV | grep usb`" ]; then  # Only USB devices
    FDISK=`fdisk -l | grep /dev/$BDEV | head -1`
    if [ ! -z "`echo $FDISK | grep FAT32`" ]; then  # Found FAT32 partition
      mount -t vfat /dev/$BDEV /mnt
      if [ "$?" = 0 ]; then
        if [ -f /mnt/$BINDIR/$SCRIPT ]; then
          cp -R /mnt/$BINDIR /tmp
          umount /mnt
          FOUND=1
          break
        else
          umount /mnt
          continue  # Haven't found the right file, try next partition
        fi
      fi
    elif [ ! -z "`echo $FDISK | grep NTFS`" ]; then  # Found NTFS partition
      ntfs-3g /dev/$BDEV /mnt
      if [ "$?" = 0 ]; then
        if [ -f /mnt/$BINDIR/$SCRIPT ]; then
          cp -R /mnt/$BINDIR /tmp
          umount /mnt
          FOUND=1
          break
        else
          umount /mnt
          continue  # Haven't found the right file, try next partition
        fi
      fi
    else
      continue  # Either wrong file system or whole drive instead of partition
    fi
  fi
  fi
done

if [ "$FOUND" = 0 ]; then
  echo -e "\033[1;35m  Could not find script $BINDIR/$SCRIPT on any USB device!\033[0m"
  exit 2
else
  echo -e "\033[1;35m  Found script $BINDIR/$SCRIPT on /dev/$BDEV\033[0m"
fi

if [ -f $TMPDIR/$BINDIR/$SCRIPT ]; then
  dos2unix $TMPDIR/$BINDIR/$SCRIPT  # Make sure the script has Unix line endings
  echo -e "\033[1;35m  Executing script $TMPDIR/$BINDIR/$SCRIPT ...\033[0m"
  source $TMPDIR/$BINDIR/$SCRIPT /dev/$BDEV
else
  echo -e "\033[1;35m  Cannot find test script $TMPDIR/$BINDIR/$SCRIPT\033[0m"
  exit 3
fi

# EOF


