#!/bin/sh

DIR=`dirname $0`
STATION=`cat /opt/pos/etc/config.ini | grep "STATION_NUMBER" | cut -f2 -d=`
HRD_BACKUP="/opt/pos/server/data/hardlock_backup"

if [ "$USER" != "root" ]; then
  echo "NOUSER - Needs to be executed as root..."
  exit
fi

if [ "$STATION" != "0" ]; then
  echo "NOSERVER - Needs to be executed in server machine"
  exit
fi

if [ ! -e "$HRD_BACKUP" ]; then
  echo "NOBACKUP - Can't find $HRD_BACKUP"
  exit
fi

for dev in `ls /dev/sd[bcdefg]`; do
  IS_MOUNTED=`mount | grep $dev`

  if [ "$IS_MOUNTED" != "" ]; then
    umount "${dev}1" 
  fi

  sfdisk $dev <<EOF
0
,
;
;
EOF

  sfdisk --change-id $dev 1 c
  mkfs.vfat -n pos "${dev}1"
  sync

  ONLY_DEV=`echo $dev | cut -f3 -d"/"`

  if [ ! -d "/media/usbhd-${ONLY_DEV}1" ]; then
    mkdir /media/usbhd-${ONLY_DEV}1
  fi

  mount "${dev}1" "/media/usbhd-${ONLY_DEV}1"

  if [ ! -d "/media/usbhd-${ONLY_DEV}1/pos" ]; then
    mkdir /media/usbhd-${ONLY_DEV}1/pos
  fi

  /opt/pos/common/bin/device_id /media/usbhd-${ONLY_DEV}1 > /media/usbhd-${ONLY_DEV}1/hardlock_id.txt
  cp $HRD_BACKUP /media/usbhd-${ONLY_DEV}1/pos/hardlock

  exit
done


