#!/bin/sh

# This bit of voodoo will get out output into /var/log/messages
#npipe=/tmp/$$.tmp
#trap "rm -f $npipe" EXIT
#mknod $npipe p
#logger < $npipe &
#exec 1>&-
#exec 1>$npipe 2>&1

exec > /dev/console 2>&1

# flashcache_create calls dmsetup which must be in the path
export PATH=/sbin:/bin:/usr/sbin:/usr/bin

# we will read a config file and set up the flashcache
# the config file is generated by the parse module
for i in $(cat /proc/cmdline) ; do
   pram=${i%%=*}
   if [ "$pram" = "rd_FLASHCACHE" ] ; then
      conf="$conf ${i#*=}"
   fi
done

echo "Running fc_scan $*"
udev_dev=$1
#set
#if [ -f /etc/flashcache.conf ] ; then
#   for fc_conf in $(cat /etc/flashcache.conf) ; do
   for fc_conf in $conf ; do
      fc_description=$fc_conf
      fc_dev="${fc_conf%%:*}"
      fc_conf="${fc_conf#*:}"
      fc_ssd="${fc_conf%%:*}"
      fc_conf="${fc_conf#*:}"
      fc_name="${fc_conf%%:*}"
      fc_conf="${fc_conf#*:}"

      if [ "$fc_dev" != "$udev_dev" ] ; then
         continue
      fi
      echo "Starting flashcache for $fc_description" 

      if [ -e "$fc_dev" -a -e "$fc_ssd" ] ; then
         if [ ! -e "/dev/mapper/$fc_name" ] ; then
            if [ "$fc_conf" = "back" ] ; then
               # how do we know if the load worked?
               # If the load fails, assume we need to create a new one (first use)
               flashcache_load "$fc_ssd" "$fc_name" || ( echo "Load failed... creating new writeback cache" && \
                  flashcache_create -v -p "$fc_conf" "$fc_name" "$fc_ssd" "$fc_dev" )
            elif [ "$fc_conf" = "none" ] ; then
               # We just want to remove any existing writeback cache
               # do we need some safety to not remove a dirty cache?
               flashcache_destroy "$fc_ssd" 
            else
               # if the create failes is might be because there is an old writeback header
               # what happens if it is dirty?
               echo Calling flashcache_create -v -p "$fc_conf" "$fc_name" "$fc_ssd" "$fc_dev"
               flashcache_create -v -p "$fc_conf" "$fc_name" "$fc_ssd" "$fc_dev" || ( echo "Create failed... removing old writeback cache" && \
                  flashcache_destroy "$fc_ssd" && sleep 2 && \
                  flashcache_create -v -p "$fc_conf" "$fc_name" "$fc_ssd" "$fc_dev" )
            fi
            sleep 1
         else
            echo "Already active" 
         fi
      else
         echo "Devices not ready"
      fi
   done
#fi
echo "fc_scan done" 
unset fc_conf
unset fc_name
unset fc_ssd
unset fc_dev

