#!/bin/bash

# Include defaults
. /usr/local/recordum/sys/defaults.include

INSTALL_STATUS="none"
SCRIPT_NAME="installhdd"
SCRIPT_DESC="Install HDD"
HWSTATUS="none"


# Redirect output?
LOG_FILE="$1"

if [ "$LOG_FILE" != "" ] && [ -f "$LOG_FILE" ] ; then
    # Redirect output
    echo "Output redirected to $LOG_FILE"
    exec 1>>$LOG_FILE 2>&1
fi



read_installstatus() {
    [ -f $INSTALLHDD_STATUSFILE ] && INSTALL_STATUS=`cat $INSTALLHDD_STATUSFILE` 
    if [ "$INSTALL_STATUS" = "finished" ] ; then
        rm $INSTALLHDD_STATUSFILE
    fi
    HWSTATUS=`$SYSINFO hwstatus`
}

set_next_step() {
    INSTALL_STATUS=$1
    echo "$INSTALL_STATUS" > $INSTALLHDD_STATUSFILE
}




read_installstatus

[ "$HWSTATUS" != "HDDATTACHED" ] && [ "$INSTALL_STATUS" = "setuphdd" ] && exit_onerror 1 "Will not invoke $INSTALL_STATUS for HDD Status: $HWSTATUS"
[ "$HWSTATUS" != "HDDMOUNTED" ] && [ "$INSTALL_STATUS" != "setuphdd" ] && [ "$INSTALL_STATUS" != "finished" ] && [ "$INSTALL_STATUS" != "none" ] && exit_onerror 1 "Can not invoke $INSTALL_STATUS for HDD Status: $HWSTATUS"

[  "$INSTALL_STATUS" = "none" ] && exit_onerror 3 "Don't know what to do, configure $INSTALLHDD_STATUSFILE"

while [ "$INSTALL_STATUS" != "none" ] && [ "$INSTALL_STATUS" != "finished" ]
do
    case "$INSTALL_STATUS" in
        setuphdd)
           verbose_out 0 "$SCRIPT_NAME: Invoking setuphdd"
           $REC_SYSDIR/setuphdd
           case "$?" in
               0)
                  verbose_out 0 "$SCRIPT_NAME: setuphdd finished successfully"
                  set_next_step "restoresys"
                  cp $FSTAB_DEFAULT /etc/fstab || exit_onerror "$?" "Could not copy $FSTAB_DEFAULT to /etc/fstab"
                  do_sysrestart
                  # break
                  exit 0
               ;;
               *)
                  exit_onerror "$?" "Exiting because of previous errors."
               ;;
           esac
        ;;
 
        restoresys)
          verbose_out 0 "$SCRIPT_NAME: Invoking restoresys"
          $REC_SYSDIR/restoresys
          ! [ "$?" -eq 0 ] && exit_onerror "$?" "Exiting because of previous errors."
          set_next_step "setupdb"
        ;;

        setupdb)
          verbose_out 0 "$SCRIPT_NAME: Invoking setupdb"
          $REC_SYSDIR/setupdb
          ! [ "$?" -eq 0 ] && exit_onerror "$?" "Exiting because of previous errors."
          set_next_step "restoredb"
        ;;
  
        restoredb)
          verbose_out 0 "$SCRIPT_NAME: Invoking restoredb"
          $REC_SYSDIR/restoredb
          ! [ "$?" -eq 0 ] && exit_onerror "$?" "Exiting because of previous errors."
          set_next_step "finished"
          do_sysrestart
          exit 0
        ;;
          
    esac
done




exit 0



