#!/bin/sh

. /lib/dracut-lib.sh

# we will read a config file and set up the flashcache
# the config file is generated by the parse module
info "Running fc_scan"
if [ -f /etc/flashcache.conf ] ; then
   for fc_conf in $(cat /etc/flashcache.conf) ; do
      info "Starting flashcache for $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 [ -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" || \
                  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 fails is might be because there is an old writeback header
               # what happens if it is dirty?
               flashcache_create -v -p "$fc_conf" "$fc_name" "$fc_ssd" "$fc_dev" || \
                 ( flashcache_destroy "$fc_ssd" && \
                   flashcache_create -v -p "$fc_conf" "$fc_name" "$fc_ssd" "$fc_dev" )
            fi
         else
            info "Already active"
         fi
      else
         info "Devices not ready"
      fi
   done
fi
info "fc_scan done"
unset fc_conf
unset fc_name
unset fc_ssd
unset fc_dev

