#!/bin/sh 

# -------------------------------------------------------
# file   : getfallback8k.sh
# purpose: get the path to fallback image for any  dir.
# author : Vittal.S
#
# usage  : getfallback8k [dir]
#
# modifications:
# 10-07-08  Initial Creation .
# -------------------------------------------------------

# -------------------------------------------------------
# function: 
# args    :  none
# description: returns the absolute patch for the fallback
#   directory. First we determine the fallback partition 
#   using sync8k and then proceed to determine the fallback.
#   Note: the srcpath passed as option is any directory,
#   in relative path not absolutely resolved path.
# -------------------------------------------------------

# -------------------------------------------------------
# function: initmap
# args    :  none
# description: 
#   creates a map of partitions to image partition.
# -------------------------------------------------------

initmap( )
{
   lhs[0]="enterprise"
   lhs[1]="global"
   lhs[2]="home"
   lhs[3]="log"
   lhs[4]="opt"
   lhs[5]="software"
   lhs[6]="tmp"
   lhs[7]="tpa"
   lhs[8]="unisphere"
   lhs[9]="var"
   lhs[10]="none"

   rhs[0]="/img/enterpriseimg"
   rhs[1]="/img/globalimg"
   rhs[2]="/img/homeimg"
   rhs[3]="/img/logimg"
   rhs[4]="/img/optimg"
   rhs[5]="/img/softwareimg"
   rhs[6]="/img/tmpimg"
   rhs[7]="/img/tpaimg"
   rhs[8]="/img/unisphereimg"
   rhs[9]="/img/varimg"
   rhs[10]="none"
}

# -------------------------------------------------------
# function: mapdir
# args    :  none
# description: 
#   maps the relative to absolute path.
# -------------------------------------------------------

mapdir( )
{
   mapfallback=$1
   mapsrc=$2
   maptail=$3
  
   mapres=""
   count=0
   while [ "${lhs[$count]}" != "none" ];
   do
      if [ "${lhs[$count]}" = "$mapsrc" ];
      then
         mapres="${rhs[$count]}"
         break;
      fi
      count=`expr $count + 1`
   done
   if [ "${mapres}" = "" ];
   then
      mapres="/img/rootimg"
   fi
   if [ "$mapres" = "/img/rootimg" ];
   then
      echo "${mapres}/${mapsrc}/${maptail}"
   else
      echo "${mapres}/${mapfallback}/${maptail}"
   fi
}

set +x
Success=0
Failure=2
srcdir=$1
active=`/unisphere/srx3000/srx/bin/sync8k -q | awk -F',' '{ print $1 }' | awk -F':' '{ print $2 }' 2>/dev/null`
if [ $? -ne 0 ];
then
   echo "Sorry, cannot determine partition information."
   exit $Failure
fi

if [ "$active" = "primary" ];
then
   fallback=secondary
else
   fallback=primary
fi

srchead="`echo $srcdir | awk -F'/' '{ print $2 }'`"
srctail="`echo $srcdir | awk -F'/' '{ for(idx=3;idx<NF;idx++) printf("%s/",$idx); }'`"

if [ "$srchead" = "img" ];
then
  echo $srcdir
  exit $Success
fi
initmap
mapdir $fallback $srchead $srctail
exit $Success

