#!/bin/sh
clear

## Declare some variables
#
tdm2Conf="/etc/3dm2/3dm2.conf"
tdm2ConfPath="/etc/3dm2"
scriptVer="v3.00.00.013"
installDir=`pwd`
argOneComplete="0"
optPrompt="Y"
oldPath=""
email=""
oldConfig=""
function=""
EmailServer=""
EmailSender=""
EmailRecipient=""


## Check if user is root
if [ "`id -u`" -ne 0 ]; then
    /bin/echo ""
    /bin/echo "You must be root or have root privilages to install 3DM2 and CLI."
    /bin/echo "3DM2/CLI installation will stop."
    /bin/echo ""
    exit 1
fi

## Source utility executables
cutPath='/usr/bin/cut'
sedPath='/usr/bin/sed'
trPath='/usr/bin/tr'
grepPath='/usr/bin/grep'
catPath='/bin/cat'
cpPath='/bin/cp'
rmPath='/bin/rm'

expPath=`echo $0 | $sedPath -e 's/\/install.sh//'` >> /dev/null
## End variable declaration


doUsage() {
     clear
     echo "         *********************************************"
     echo "         *   Arguments supported with install.sh     *"
     echo "         *********************************************"
     echo "The following arguments are supported for use with the Install.3dm script."
     echo ""
     echo "-i or --install will install 3DM2 and CLI files and create needed configuration files."
     echo ""
     echo "-u or --uinstall will remove all 3DM2 and CLI components and configuration files."
     echo ""
     echo "-f will run install/unistall without prompts to conftinue."
     echo ""
     echo "If you use -f with -i or --install you will need to also provide additional options. "
     echo ""
     echo "Force options:"
     echo "N|Y - Tells installer to keep existing 3dm2.conf or install a new one with default values."
     echo "      If N option is provided you will need to provide 0|1 option as well."
     echo "           0|1 - 0 installs 3dm2 with GUI mode, 1 - defines Logger mode."
     echo "      Y option tells installer to use existing 3dm2.conf if it exists, if not present a "
     echo "           default version will be installed."
     echo ""
     echo "*** Any other options will print the usage screen. ***"
     echo ""
     echo "Example (./install.sh -i or ./install.sh --install)"
     echo "Example (./install.sh -u or ./install.sh --uinstall)"
     echo "Example (./install.sh -i -f[N[0|1]|Y] or ./install.sh --install -f[N[0|1]|Y])"
     echo "Example (./install.sh -u -f or ./install.sh --uinstall -f)"
     echo ""
     exit 0
}


## Parse Args
#
if [ $# -gt 0 ]; then
    argOne=`echo $1 | $trPath /A-Z/ /a-z/` >> /dev/null

    case "$argOne" in
        -i|--install)
            argOneComplete="1"
            optSelect="-i"
            ;;
        -u|--uninstall)
            argOneComplete="1"
            optSelect="-u"
            ;;
        *)
          ;;
    esac
fi


## Parse force arg and options.
if [ $# -gt 1 ] && [ "$argOneComplete" = "1" ]; then
    ## Parse out force option
    argTwoOne="`echo $2 | $cutPath -c2 | $trPath /F/ /f/`" >> /dev/null
    ## Add - back to force option
    argTwoOne="`echo $2 | $cutPath -c1`$argTwoOne" >> /dev/null
    ## Parse out keep old config option
    argTwoTwo="`echo $2 | $cutPat -c3 | $trPath /NY/ /ny/`" >> /dev/null
    ## Parse out 3dm2 GUI/Logger option
    argTwoThree="`echo $2 | $cutPath -c4`" >> /dev/null

    case "$argTwoOne" in
        -f)
           optPrompt="N"
           if [ "$optSelect" != "-u" ]; then
               case "$argTwoTwo" in
                   y)
                     if [ -e $tdm2Conf ]; then
                         oldConfig="Y"
                     else
                         oldConfig="N"
                         function="0"
                     fi
                     ;;
                   n)
                     oldConfig="N"
                     ;;
                   *)
                     doUsage;
                     ;;
               esac
               if [ "$oldConfig" = "N" -a -z "$function" ]; then
                   case "$argTwoThree" in
                       0)
                         function="0"
                         ;;
                       1)
                         function="1"
                         ;;
                       *)
                         doUsage;
                         ;;
                   esac
               fi
           fi
           ;;
        *)
          doUsage;
          ;;
    esac
fi
## End Parse Args


## Check OS type and get architecture
uname -a | $trPath /A-Z/ /a-z/ | $grepPath "i[3-6]86" >> /dev/null
if [ $? -eq 0 ]; then
    arch="x86"
fi

uname -a | $trPath /A-Z/ /a-z/ | $grepPath "x86_64" >> /dev/null
if [ $? -eq 0 ]; then
    arch="x86_64"
fi

uname -a | $trPath /A-Z/ /a-z/ | $grepPath "amd64" >> /dev/null
if [ $? -eq 0 ]; then
    arch="x86_64"
fi

release=`uname -s`
osver=`uname -r | $cutPath -d '.' -f1` >> /dev/null
if [ "$release" != "FreeBSD" ] || [ "$osver" -lt "6" ] || [ "$arch" != "x86" -a "$arch" != "x86_64" ]; then
     /bin/echo ""
     /bin/echo "Only FreeBSD 6.x and newer on x86 or x86_64 is supported by this script. Your"
     /bin/echo "system is running $release `uname -r` on `uname -m`, the script will now exit."
     /bin/echo ""
     exit 1
else
    if [ "$osver" -gt "6" ]; then
        osver="7x"
    else
        osver="6x"
    fi
fi


## Start function definition
doUninstall() {
     echo ""
     echo "-----------------------------------------"
     echo " Checking for components to remove.      "
     echo " This script will stop and disable the   "
     echo " 3DM2 service and uninstall 3DM2/CLI     "
     echo " files and directories. It will display  "
     echo " display a list of files and directories "
     echo " to be removed prior to removal.         "
     echo "-----------------------------------------"

     if [ -e $tdm2Conf ]; then
         ## Start creating list of files to remove
         echo "********************************************"
         echo "**  3ware tools directory to be removed.  **"
         echo "********************************************"

         appPath=`$catPath $tdm2Conf | $grepPath -i msgpath | $grepPath -i 3ware | $sedPath -e 's/MsgPath //' | $sedPath -e 's/\/3DM2\/msg//'` >> /dev/null
         if [ -d $appPath ]; then
             echo "Root install path: $appPath"
             echo ""
         fi

         echo "*********************************************"
         echo "**  3DM2 files/directories to be removed.  **"
         echo "*********************************************"
         if [ -e /usr/sbin/3dm2 -o -h /usr/sbin/3dm2 ]; then
             echo "3DM2 sym link: /usr/sbin/3dm2"
         fi

         ls /var/log/tdm_aen* >> /dev/null
         if [ $? -eq 0 ]; then
             echo "3dm2 AEN logs: /var/log/tdm_aen*"
         fi

         tdm2Path=`$catPath $tdm2Conf | $grepPath -i msgpath | $grepPath -i 3ware | $sedPath -e 's/MsgPath //' | $sedPath -e 's/\/msg//'` >> /dev/null
         tdm2ConfPath=`echo $tdm2Conf | $sedPath -e 's/\/3dm2.conf//'` >> /dev/null
         echo "3DM2 files: $tdm2Path"
         echo "3DM2 config files: $tdm2ConfPath"

     echo ""
     echo "********************************************"
     echo "**  CLI files/directories to be removed.  **"
     echo "********************************************"
     if [ -e /usr/sbin/tw_cli -o -h /usr/sbin/tw_cli ]; then
          echo "CLI sym link: /usr/sbin/tw_cli"
     fi

     if [ -e /usr/share/man/man8/tw_cli.8.nroff ]; then
         echo "CLI man page file: /usr/share/man/man8/tw_cli.8.nroff"
     fi

     cliPath=`$catPath $tdm2Conf | $grepPath -i msgpath | $grepPath -i 3ware | $sedPath -e 's/MsgPath //' | $sedPath -e 's/3DM2\/msg/CLI/'` >> /dev/null
     if [ -d $cliPath ]; then
         echo "CLI files: $cliPath"
     fi

     if [ "$optPrompt" = "Y" ]; then
         echo ""
         read -p "Press 'Enter Key' to continue uninstall or Control C to exit. " waitExit
     fi


     ## Start uninstall
     #
     ps ax | $grepPath '3dm2' | $grepPath -v 'grep' >> /dev/null
     if [ $? -eq 0 ]; then
         if [ -e /etc/rc.d/tdm2 ]; then
             echo "**** Stopping 3DM2 Service to allow uninstall. ****"
             /etc/rc.d/tdm2 forcestop
             if [ $? -ne 0 ]; then
                 echo "Failed to stop 3dm2 serverice."
             fi
         fi
     fi

     ## Change to install root directory
     echo -n "Change directory to $appPath to start uninstall... "
     cd $appPath
     if [ $? -ne 0 ]; then
         echo "Failed to change directory, installer exiting..."
         exit 1
     else
         echo "done."
     fi

     if [ -e /usr/sbin/3dm2 -o -h /usr/sbin/3dm2 ]; then
         echo "Removing 3DM2 symbolic link: /usr/sbin/3dm2..."
         $rmPath -fv /usr/sbin/3dm2
         if [ $? -ne 0 ]; then
             echo "Failed to remove symbolic link."
         else
             echo "done."
         fi
     fi

     ls /var/log/tdm_aen* >> /dev/null
     if [ $? -eq 0 ]; then
         /echo "Removing 3dm2 AEN logs: /var/log/tdm_aen*"
         $rmPath -fv /var/log/tdm_aen*
         if [ $? -ne 0 ]; then
             echo "Failed to remove AEN logs."
         else
             echo "done."
         fi
     fi

     if [ -e $tdm2Conf ]; then
         tdm2MsgPath=`$catPath $tdm2Conf | $grepPath -i msgpath | $grepPath -i 3ware | $sedPath -e 's/MsgPath //'` >> /dev/null
         tdm2HelpPath=`$catPath $tdm2Conf | $grepPath -i help | $grepPath -i 3ware | $sedPath -e 's/Help //'` >> /dev/null
         tdm2Path=`$catPath $tdm2Conf | $grepPath -i msgpath | $grepPath -i 3ware | $sedPath -e 's/MsgPath //' | $sedPath -e 's/\/msg//'` >> /dev/null
         tdm2ConfPath=`echo $tdm2Conf | $sedPath -e 's/\/3dm2.conf//'` >> /dev/null
         cliPath=`$catPath $tdm2Conf | $grepPath -i msgpath | $grepPath -i 3ware | $sedPath -e 's/MsgPath //' | $sedPath -e 's/3DM2\/msg/CLI/'` >> /dev/null

         if [ -d $appPath/3DM2/msg ]; then
             cd $appPath/3DM2
             if [ $? -eq 0 ]; then
                 echo "Removing 3DM2 message files directory: $tdm2MsgPath"
                 $rmPath -fvr ./msg
                 if [ $? -ne 0 ]; then
                     echo "Failed to remove directory."
                 else
                     echo "done."
                 fi
             fi
         fi

         if [ -d $appPath/3DM2/help ]; then
             cd $appPath/3DM2
             if [ $? -eq 0 ]; then
                 echo "Removing 3DM2 help files directory: $tdm2HelpPath"
                 $rmPath -fvr ./help
                 if [ $? -ne 0 ]; then
                     echo "Failed to remove directory."
                 else
                     echo "done."
                 fi
             fi
         fi

         if [ -d $appPath/3DM2 ]; then
             cd $appPath
             if [ $? -eq 0 ]; then
                 echo "Removing 3DM2 files and directory: $tdm2Path"
                 $rmPath -fvr ./3DM2
                 if [ $? -ne 0 ]; then
                     echo "Failed to remove directory."
                 else
                     echo "done."
                 fi
             fi
         fi

         if [ -d $tdm2ConfPath ]; then
             cd /etc
             if [ $? -eq 0 ]; then
                 echo "Removing 3DM2 config directory and files: $tdm2ConfPath"
                 $rmPath -fvr ./3dm2
                 if [ $? -ne 0 ]; then
                     echo "Failed to remove files."
                 else
                     echo "done."
                 fi
             fi
         fi

         if [ -e /etc/rc.d/tdm2 ]; then
             cd ./rc.d
             if [ $? -eq 0 ]; then
                 echo "Removing 3DM2 init script"
                 $rmPath -fv ./tdm2
                 if [ $? -ne 0 ]; then
                     echo "Failed to remove script."
                 else
                     echo "done."
                 fi
             fi
         fi

         if [ -d $cliPath ]; then
             cd $appPath
             if [ $? -eq 0 ]; then
                 echo "Removing CLI directory and files: $cliPath"
                 $rmPath -fvr ./CLI
                 if [ $? -ne 0 ]; then
                     echo "Failed to remove files."
                 else
                     echo "done."
                 fi
             fi
         fi

         if [ -e /usr/sbin/tw_cli -o -h /usr/sbin/tw_cli ]; then
             echo "Removing CLI sym link: /usr/sbin/tw_cli"
             $rmPath -fv /usr/sbin/tw_cli
             if [ $? -ne 0 ]; then
                 echo "Failed to remove symbolic link."
             else
                 echo "done."
             fi
         fi
     fi

     if [ -e /usr/share/man/man8/tw_cli.8.nroff ]; then
         echo "Removing CLI man page file: /usr/share/man/man8/tw_cli.8.nroff"
         $rmPath -fv /usr/share/man/man8/tw_cli.8.nroff
         if [ $? -ne 0 ]; then
             echo "Failed to remove man page file."
         else
             echo "done."
         fi
     fi

     if [ -d $appPath ]; then
         cd $appPath/..
         if [ $? -eq 0 ]; then
             echo "Removing 3ware directory and files: ($appPath)..."
             $rmPath -fvr ./3ware
             if [ $? -ne 0 ]; then
                 echo "Failed to remove files."
             else
                 echo "done."
             fi
         fi
     fi
  else
      echo "Done, nothing found to uninstall."
  fi
  ## End uninstall
  exit 0
}


configureEmail() {
     ## Update EmailServer
     echo ""
     read -p "Enter email server name: " email
     while [ -z $email ]
     do
        echo ""
        echo "You must enter an email server name"
        read -p "Enter email server name: " email
     done
     EmailServer=$email
     echo "Updating 3dm2.conf EmailServer= with EmailServer=$EmailServer"

     ## Update EmailSender
     email=""
     echo ""
     read -p "Enter sender email address: " email
     while [ -z $email ]
     do
        echo ""
        echo "Invalid email address entered : $email"
        read -p "Enter sender email address: " email
     done
     EmailSender=$email
     echo "Updating 3dm2.conf EmailSender= with EmailSender=$EmailSender"

     ## Update EmailRecipient
     email=""
     echo ""
     read -p "Enter recipient email address: " email
     while [ -z $email ]
     do
        echo ""
        echo "Invalid email address entered : $email"
        read -p "Enter recipient email address: " email
     done
     EmailRecipient=$email
     echo "Updating 3dm2.conf EmailRecipient= with EmailRecipient=$EmailRecipient"
}


showLicense() {

     clear
     echo "STOP! BEFORE YOU INSTALL THIS SOFTWARE CAREFULLY READ THIS SOFTWARE LICENSE AGREEMENT."
     echo " "
     echo "Installing this Software indicates that you agree to abide by this Software License Agreement. If you do not agree with it, promptly return the Software and we will refund the purchase price."
     echo " "
     echo "                       Software License Agreement"
     echo " "
     echo "PLEASE READ CAREFULLY BEFORE STARTING INSTALLATION OF THE SOFTWARE"
     echo " "
     echo "THE SOFTWARE AND DOCUMENTATION PROVIDED HEREIN IS PROPRIETARY TO LSI CORPORATION AND ITS LICENSORS.  LSI CORPORATION IS WILLING TO LICENSE THE SOFTWARE AND DOCUMENTATION TO YOU ONLY UPON THE CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS SOFTWARE LICENSE AGREEMENT.   BY USING THIS SOFTWARE, YOU, THE END-USER, AGREE TO THE LICENSE TERMS BELOW.  IF YOU DO NOT AGREE TO THESE TERMS, YOU MAY NOT USE THE SOFTWARE."
     echo " "
     echo "1.   Grant of License"
     echo " "
     echo "Conditioned upon compliance with the terms and conditions of this Software License Agreement (.Agreement.), LSI Corporation ("LSI") grants you, the original licensee, a nonexclusive and nontransferable limited license to use for your internal business purposes the Software and the Documentation for the number and type of installations for which you have paid the required license fees (.Permitted Use.). You may make only one (1) copy of the Software solely for backup or archival purposes. You may not copy any of the written material accompanying the Software (.Documentation.)."
     echo " "
     echo "2.   License Conditions; Confidentiality  "
     echo " "
     echo "The Software and Documentation are confidential information of Licensor and its licensors.  Except for the Permitted Use, You may not disclose or give copies of the Software or Documentation to others and you may not let others gain access to the same.  You may not post the Software or Documentation, or otherwise make available, in any form, on the Internet or in other public places or media.  You may not modify, adapt, translate, rent, lease, loan, distribute or resell for profit, or create derivative works based upon, the Software or Documentation or any part of thereof, but you may transfer the original diskette (s) of the Software and Documentation on a one-time basis provided you retain no copies of the Software and Documentation and the recipient assumes all of the terms of this Agreement. You may not reverse engineer, decompile, disassemble or otherwise attempt to derive source code from the Software except to the extent allowed by law."
     echo " "
     echo "3.   Limited Warranty"
     echo " "
     echo "LSI grants a limited warranty only to the original licensee, that the Software will perform substantially in accordance with the Documentation prepared by LSI for a period of ninety (90) days from the date of receipt by the original licensee. LSI.s entire liability and the licensee's exclusive remedy for breach of the limited warranty above shall be, at LSI.s sole option and discretion, either: (a) repair or replacement of the non-conforming Software which is returned to LSI and determined by LSI to be non-conforming, or (b) return of the price you paid solely for the Software. The limited warranty is void if non-conformity of the Software results from accident, abuse, negligence, misapplication, or failure to use the Software in accordance with the Permitted Use or the Documentation. Any replacement Software will be warranted to the original licensee for the remainder of the original warranty period, or thirty (30) days, whichever is longer. This limited warranty gives you specific legal rights. You may have others which vary from state to state. Some states do not allow limitation of duration of an implied warranty, so the above limitations may not apply to you.  EXCEPT AS SPECIFIED EXPRESSLY IN THIS LIMITED WARRANTY, ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, AND WARRANTIES INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, SATISFACTORY QUALITY, NON-INTERFERENCE, ACCURACY OF INFORMATIONAL CONTENT, OR ARISING FROM A COURSE OF DEALING, LAW, USAGE, OR TRADE PRACTICE, ARE HEREBY EXCLUDED TO THE EXTENT ALLOWED BY APPLICABLE LAW AND ARE EXPRESSLY DISCLAIMED BY LSI, ITS SUPPLIERS AND LICENSORS.  TO THE EXTENT AN IMPLIED WARRANTY CANNOT BE EXCLUDED, SUCH WARRANTY IS LIMITED IN DURATION TO THE EXPRESS WARRANTY PERIOD.  BECAUSE SOME STATES OR JURISDICTIONS DO NOT ALLOW LIMITATIONS ON HOW LONG AN IMPLIED WARRANTY LASTS, THE ABOVE LIMITATION MAY NOT APPLY. THIS WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS, AND YOU MAY ALSO HAVE OTHER RIGHTS WHICH VARY FROM JURISDICTION TO JURISDICTION.  This disclaimer and exclusion shall apply even if the express warranty set forth above fails of its essential purpose.  "
     echo " "
     echo "4.   LIMITATION OF LIABILITY AND REMEDIES"
     echo " "
     echo "IN NO EVENT SHALL LSI OR ITS LICENSORS BE LIABLE TO YOU FOR ANY INDIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL OR SPECIAL DAMAGES ARISING FROM THIS AGREEMENT OR THE USE OF THE SOFTWARE OR DOCUMENTATION (INCLUDING, WITHOUT LIMITATION, DAMAGE FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, LOSS OF GOODWILL, OR OTHER PECUNIARY LOSS), WHETHER RESULTING FROM LSI'S NEGLIGENCE OR OTHERWISE, EVEN IF LSI WAS ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  LSI'S MAXIMUM LIABILITY FOR ANY DAMAGES ARISING UNDER THIS AGREEMENT AND THE USE OF THE SOFTWARE AND DOCUMENTATION WILL NOT EXCEED AN AMOUNT EQUAL TO THE LICENSE FEES YOU PAID TO LSI FOR THE SOFTWARE AND DOCUMENTATION.  THE LAWS OF SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY, AND THE ABOVE EXCLUSION MAY NOT APPLY TO YOU."
     echo " "
     echo "5.   U.S. Government End User Purchasers  "
     echo " "
     echo "The Software and Documentation qualify as "commercial items," as that term is defined at Federal Acquisition Regulation (.FAR.) (48 C.F.R.) 2.101, consisting of "commercial computer software" and "commercial computer software documentation" as such terms are used in FAR 12.212.  Consistent with FAR 12.212 and DoD FAR Supp. 227.7202-1 through 227.7202-4, and notwithstanding any other FAR or other contractual clause to the contrary, you may provide to Government end user or, if this Agreement is direct, Government end user will acquire, the Software and Documentation with only those rights set forth in this Agreement. Use of either the Software or Documentation or both constitutes agreement by the Government that the Software and Documentation are .commercial computer software. and .commercial computer software documentation,. and constitutes acceptance of the rights and restrictions herein."
     echo " "
     echo "6.   Term; Termination  "
     echo " "
     echo "You may terminate this Agreement at any time, and it will automatically terminate if you fail to comply with it.  If terminated, you must immediately destroy the Documentation and the Software and all copies you have made."
     echo " "
     echo "7.  Audit Rights  "
     echo " "
     echo "LSI shall have the right on reasonable notice, at its own cost and no more than once per year, directly or through its independent auditors, to inspect, examine, take extracts, and make copies from, your records to the extent reasonably necessary to verify your compliance with the terms and conditions of this Agreement. This right shall apply during the term of this Agreement and for one (1) year thereafter."
     echo " "
     echo "8.  Export  "
     echo " "
     echo "You may not export this Software or Documentation, unless you have complied with applicable United States and foreign government laws."
     echo " "
     echo "9.  General  "
     echo " "
     echo "You assume full responsibility for the legal and responsible use of the Software and Documentation.  You agree that this Agreement is the complete agreement between you and LSI (and that any verbal or written statements that are not reflected in this Agreement, and any prior agreements, are superseded by this Agreement).  To be effective, any amendment of this Agreement must be in writing and signed by both you and LSI.  Should any provisions of this Agreement be held to be unenforceable, then such provision shall be separable from this Agreement and shall not effect the remainder of the Agreement.  This Agreement shall be governed by California law, not including its choice of law provisions.  The United Nations Convention on the International Sale of Goods shall not be applied to this Agreement.  All rights in the Software and Documentation not specifically granted in this Agreement are reserved by LSI or its licensors.  The English language version of this Agreement shall be the official version.  The terms and conditions of this Software License Agreement shall be binding upon you and your respective heirs, successors and assigns."
     echo " "
     echo "10.  Survival  "
     echo " "
     echo "The provisions of Sections 2, 3, 4, 7, 8 and 9 shall survive any termination of this Agreement."
     echo " "
     echo " "
     echo " "

     read -p "Press Y to accept the License Agreement or N to exit: " licAccept
     licAccept="`echo "${licAccept}" | $trPath -cd '[:alpha:]' | $trPath /a-z/ /A-Z/`" >> /dev/null
     if [ "$licAccept" != "Y" ]; then
         echo ""
         echo "EULA not accepted. Installer exiting..."
         exit 1
     fi
}


checkOld3dm2(){
     ## Check for 3DM2 InstallShield installation.
     if [ -e /etc/3dm2/3dm2.conf -a "$oldConfig" != "N" ]; then
         echo ""
         echo "*****************************************************"
         echo "*  Checking for old version of 3DM. Please wait...  *"
         echo "*****************************************************"
         echo ""

         $catPath /etc/3dm2/3dm2.conf | $grepPath -i 'msgpath' | $grepPath -i 'amcc' >> /dev/null
         if [ $? -eq 0 ]; then
             oldPath=`$catPath /etc/3dm2/3dm2.conf | $grepPath -i 'msgpath' | $grepPath -i 'amcc' | $sedPath -e 's/MsgPath //' | $sedPath -e 's/\/3DM2\/msg/\/_uninst/'` >> /dev/null
         fi

         $catPath /etc/3dm2/3dm2.conf | $grepPath -i 'msgpath' | $grepPath -i '3ware' >> /dev/null
         if [ $? -eq 0 ]; then
             oldPath=`$catPath /etc/3dm2/3dm2.conf | $grepPath -i 'msgpath' | $grepPath -i '3ware' | $sedPath -e 's/MsgPath //' | $sedPath -e 's/\/3DM2\/msg/\/_uninst/'` >> /dev/null
         fi

         if [ -d $oldPath ]; then
             echo "An older 3DM2/CLI package is installed that is incompatible with this installation package."
             echo "Please uninstall the tool set installed at $oldPath"
             echo ""
             read -p "Installation will now exit, press 'Enter Key' to continue. " waitExit
             exit 1
         fi
     fi
}


checkOldConfig() {
     ## Check for old 3dm2.config
     if [ -e $tdm2Conf -a "$optPrompt" = "Y" ]; then
         echo ""
         echo -n "An old $tdm2Conf file was found. Do you want to use the old one? (Y|N) "
         while [ "$oldConfig" != "N" -a "$oldConfig" != "Y" ]
         do
            read oldConfig
            oldConfig="`echo "${oldConfig}" | $trPath -cd '[:alpha:]' | $trPath /a-z/ /A-Z/`" >> /dev/null
            case "$oldConfig" in
               Y) 
                  echo ""
                  echo "*** Keeping existing 3DM2 Configuration file. ***"
                  oldConfig="Y"
                  break ;;
               N) 
                  echo ""
                  echo "*** Replacing existing 3DM2 Configuration file. ***"
                  oldConfig="N"
                  break ;;
               *);;
            esac
            echo ""
            echo "Invalid option (Y|N)"
         done
     fi
}


checkLogger() {
     if [ "$optPrompt" = "Y" -a "$oldConfig" = "" -o "$optPrompt" = "Y" -a "$oldConfig" = "N" ]; then
         ## Check if user wants Logger only.
         echo ""
         echo "3DM2 supports two modes of operation."
         echo "-------------------------------------"
         echo "0 - 3DM2 with WEB interface"
         echo "1 - 3DM2 Error/Event Logger only"
         echo ""
         echo -n "Which version of 3DM would you like configured? (0|1) "

         while [ "$function" != "0" -a "$function" != "1" ]
         do
            read function
            function="`echo "${function}" | $trPath -cd '[:digit:]'`" >> /dev/null
            case "$function" in
                0)
                   echo ""
                   echo "*** 3DM2 selected. ***"
                   echo ""
                   echo "*** Installing 3DM2 and CLI ***"
                   echo ""
                   break;;
                1)
                   echo ""
                   echo "*** 3ware Logger selected. ***"
                   echo ""
                   echo "*** Installing 3ware Logger and CLI ***"
                   echo ""
                   configMail="Y"
                   break;;
                *);;
            esac
            echo ""
            echo "Invalid option (0|1)"
         done

     elif [ "$optPrompt" = "N" -a "$oldConfig" = "Y" ]; then
           if [ $tdm2Conf ]; then
               ## Get current Logger setting
               $catPath $tdm2Conf | $grepPath 'Logger' >> /dev/null
               if [ $? -eq 0 ]; then
                   $catPath $tdm2Conf | $grepPath 'Logger' | $cutPath -d ' ' -f2 | $grepPath '1' >> /dev/null
                   if [ $? -eq 0 ]; then
                       function="1"
                   else
                       function="0"
                   fi
               else
                   function="0"
               fi
           else
               function="0"
           fi
     fi
     if [ "$optPrompt" = "Y" ]; then
         echo ""
         read -p "Press 'Enter Key' to continue with installation or Control C to exit. " waitExit
     fi
}


setupInstall() {
     ## Upack files into /tmp so we can run this directly from the CD.
     # Check for old /tmp/3ware directory
     if [ -d /tmp/3ware ]; then
         echo ""
         echo -n "Removing old installation files from /tmp/3ware... "
         $rmPath -rfv /tmp/3ware
         if [ $? -ne 0 ]; then
             echo "Unable to remove old installation files from /tmp/3ware, installer exiting..."
             exit 1
         else
             echo "done." 
         fi
     fi

     echo ""
     echo -n "Creating installation tmp directory /tmp/3ware... "
     mkdir -p /tmp/3ware
     if [ $? -ne 0 ]; then
         echo "Unable to create installation tmp directory /tmp/3ware, installer exiting..."
         exit 1
     else
         echo "done."
     fi

     if [ ! -e $installDir/tdmCliBSD.tgz ]; then
         if [ ! -e $installDir/packages/installers/tools/freebsd/tdmCliBSD.tgz ]; then
             if [ ! -e $expPath/tdmCliBSD.tgz ]; then
                 echo ""
                 echo "tdmCliBSD.tgz installation package not found, installer exiting..."
                 exit 1
             else
                 echo ""
                  echo -n "Extracting installation files to /tmp/3ware... "
                  tar zxf $expPath/tdmCliBSD.tgz -C /tmp/3ware >> /dev/null
                  if [ $? -ne 0 ]; then
                      echo "Failed, installer exiting..."
                      exit 1
                  else
                      echo "done."
                  fi
             fi
         else
             echo ""
              echo -n "Extracting installation files to /tmp/3ware... "
              tar zxf $installDir/packages/installers/tools/freebsd/tdmCliBSD.tgz -C /tmp/3ware >> /dev/null
              if [ $? -ne 0 ]; then
                  echo "Failed, installer exiting..."
                  exit 1
              else
                  echo "done."
              fi
         fi
     else
         echo ""
          echo -n "Extracting installation files to /tmp/3ware... "
          tar zxf $installDir/tdmCliBSD.tgz -C /tmp/3ware >> /dev/null
          if [ $? -ne 0 ]; then
              echo "Failed, installer exiting..."
              exit 1
          else
              echo "done."
          fi
     fi

     echo ""
     echo -n "Changing directory to /tmp/3ware to continue installation "
     cd /tmp/3ware
     if [ $? -ne 0 ]; then
         echo "Failed, installer exiting..."
         exit 1
     else
         echo "done."
     fi

     ## Create 3dm2 config path
     if [ ! -d /etc/3dm2 ]; then
         echo -n "Creating 3dm2 configuration directory (/etc/3dm2)... "
         mkdir -p /etc/3dm2
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Create 3DM2 install path
     if [ ! -d /opt/3ware/3DM2 ]; then
         echo -n "Creating 3dm2 install path (/opt/3ware/3DM2)... "
         mkdir -p /opt/3ware/3DM2
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Create msg files path
     if [ ! -d /opt/3ware/3DM2/msg ]; then
         echo -n "Creating 3dm2 message file install path (/opt/3ware/3DM2/msg)... "
         mkdir -p /opt/3ware/3DM2/msg
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Create help files path
     if [ ! -d /opt/3ware/3DM2/help ]; then
         echo -n "Creating 3dm2 help file install path (/opt/3ware/3DM2/help)... "
         mkdir -p /opt/3ware/3DM2/help
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Create CLI install path
     if [ ! -d /opt/3ware/CLI ]; then
         echo -n "Creating CLI install path (/opt/3ware/CLI)... "
         mkdir -p /opt/3ware/CLI
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi
}


doInstall() {
     ## Install 3DM2
     echo ""
     echo "******************************************"
     echo "**** Installing 3DM2 files for $arch "
     echo "******************************************"
     echo ""

     ## Copy install script to install base dir
     if [ ! -e $installDir/install.sh ]; then
         if [ ! -e $installDir/packages/installers/tools/freebsd/install.sh ]; then
             if [ ! -e $expPath/install.sh ]; then
                 echo "Failed to copy install.sh to /opt/3ware... Installer exiting."
                 exit 1
             else
                 echo -n "Copying install.sh to /opt/3ware... "
                 $cpPath -f $expPath/install.sh /opt/3ware
                 if [ $? -ne 0 ]; then
                     echo "Failed, installer exiting..."
                     exit 1
                 else
                     echo "done."
                 fi
             fi
         else
             echo -n "Copying install.sh to /opt/3ware... "
             $cpPath -f $installDir/packages/installers/tools/freebsd/install.sh /opt/3ware
             if [ $? -ne 0 ]; then
                 echo "Failed, installer exiting..."
                 exit 1
             else
                 echo "done."
             fi
         fi
     else
         echo -n "Copying install.sh to /opt/3ware... "
         $cpPath -f $installDir/install.sh /opt/3ware
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Install 3DM2 binary
     if [ -e ./$osver/3dm2.$arch ]; then
         echo -n "Installing 3dm2 binary to /opt/3ware/3DM2... "
         $cpPath -f ./$osver/3dm2.$arch /opt/3ware/3DM2/3dm2
         if [ $? -ne 0 ]; then
             echo "Failed installer exiting..."
             exit 1
         else
             echo "done."
         fi
         echo -n "Setting runtime permissions for /opt/3ware/3DM2/3dm2... "
         chmod 755 /opt/3ware/3DM2/3dm2 >> /dev/null
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     else
         echo ""
         echo "./$osver/3dm2.$arch binary missing, installer exiting..."
         exit 1
     fi

     ## Install 3DM2 message files
     if [ -f ./tdm2Msg.tgz ]; then
         echo -n "Installing 3dm2 message files to /opt/3ware/3DM2/msg... "
         tar zxf ./tdm2Msg.tgz -C /opt/3ware/3DM2/msg >> /dev/null 
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Install 3DM2 help files
     if [ -f ./tdm2Help.tgz ]; then
         echo -n "Installing 3dm2 help files to /opt/3ware/3DM2/help... "
         tar zxf ./tdm2Help.tgz -C /opt/3ware/3DM2/help >> /dev/null
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi
     if [ "$oldConfig" != "Y" -a -e ./3dm2.conf ]; then
         echo -n "Installing 3dm2 configuration file to /etc/3dm2... "
         $cpPath -f ./3dm2.conf /etc/3dm2
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Install 3DM2 logo file
     if [ -e ./logo.gif ]; then
         $cpPath -f ./logo.gif /etc/3dm2
         echo -n "Installing 3dm2 logo file to /etc/3dm2... "
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Install tdm2 init scripts.
     if [ -e /etc/rc.d/tdm2 ]; then
         echo -n "Removing old init script /etc/rc.d/tdm2... "
         $rmPath -fv /etc/rc.d/tdm2 >> /dev/null
         if [ $? -ne 0 ]; then
             echo "Failed..."
         else
             echo "done."
         fi
     fi

     if [ -e ./tdm2 ]; then
         echo -n "Installing /etc/rc.d/tdm2 script... "
         $cpPath -f ./tdm2 /etc/rc.d/tdm2
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
         echo -n "Setting runtime permissions for /etc/rc.d/tdm2... "
         chmod 755  /etc/rc.d/tdm2
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Install CLI
     echo ""
     echo "******************************************"
     echo "**** Installing CLI files for $arch "
     echo "******************************************"
     echo ""

     ## Install CLI binary
     if [ -e ./tw_cli.$arch ]; then
         echo -n "Installing CLI binary to /opt/3ware/CLI/tw_cli... "
         $cpPath -f ./tw_cli.$arch /opt/3ware/CLI/tw_cli
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
         echo -n "Setting runtime permissions for /opt/3ware/CLI/tw_cli... "
         chmod 755 /opt/3ware/CLI/tw_cli
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     else
         echo ""
         echo "CLI.$arch binary missing, installer exiting..."
         exit 1
     fi

     ## Install CLI html help
     if [ -e ./tw_cli\.8\.html ]; then
         echo -n "Installing CLI html help to /opt/3ware/CLI... "
         $cpPath -f ./tw_cli\.8\.html /opt/3ware/CLI
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     ## Install CLI man page
     if [ -e ./tw_cli\.8\.nroff ]; then
         echo -n "Installing CLI man page to /usr/share/man/man8... "
         $cpPath -f ./tw_cli\.8\.nroff /usr/share/man/man8
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi
}


doConfig() {
     echo ""
     echo "***************************************"
     echo "**** Configuring CLI & 3DM2 "
     echo "***************************************"
     echo ""

     ## Create symbolic link /usr/sbin/3dm2 -> /opt/3ware/3DM2/3dm2
     if [ -e /usr/sbin/3dm2 ]; then
         echo -n "Removing old /usr/sbin/3dm2 symbolic link... "
         $rmPath -f /usr/sbin/3dm2 >> /dev/null
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
         else
             echo "done."
         fi
     fi

     echo -n "Creating /usr/sbin/3dm2 symbolic link to /opt/3ware/3DM2/3dm2... "
     ln -fs /opt/3ware/3DM2/3dm2 /usr/sbin/3dm2 >> /dev/null
     if [ $? -ne 0 ]; then
         echo "Failed, installer exiting..."
         exit 1
     else
         echo "done."
     fi

     ## Create symbolic link /usr/sbin/tw_cli -> /opt/3ware/CLI/tw_cli
     if [ -e /usr/sbin/tw_cli ]; then
         echo -n "Removing old /usr/sbin/tw_cli symbolic link... "
         $rmPath -f /usr/sbin/tw_cli >> /dev/null
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi

     echo -n "Creating /usr/sbin/tw_cli symbolic link to /opt/3ware/CLI/tw_cli... "
     ln -fs /opt/3ware/CLI/tw_cli /usr/sbin/tw_cli >> /dev/null
     if [ $? -ne 0 ]; then
         echo "Failed, installer exiting..."
         exit 1
     else
         echo "done."
     fi

     # Set permissions for 3dm2.conf
     if [ -e $tdm2Conf ]; then
         echo -n "Setting runtime permissions for $tdm2Conf... "
         chmod 600 $tdm2Conf >> /dev/null
         if [ $? -ne 0 ]; then
             echo "Failed, installer exiting..."
             exit 1
         else
             echo "done."
         fi
     fi
}


doFinish() {
     echo ""
     echo "***************************************"
     echo "**** Finishing Installation "
     echo "***************************************"
     echo ""

     ## Check for Logger setting in /etc/3dm2/3dm2.conf
     if [ "$function" = "1" ]; then
         ## Update 3dm2.conf Logger setting to enable Logger
         $catPath $tdm2Conf | $grepPath 'Logger' >> /dev/null
         if [ $? -eq 0 ]; then
             $catPath $tdm2Conf | $grepPath 'Logger' | $cutPath -d ' ' -f2 | $grepPath '0' >> /dev/null
             if [ $? -eq 0 ]; then
                 $sedPath -i -e s/'Logger 0'/'Logger 1'/ $tdm2Conf
             fi
         else
             echo "Logger 1" >> $tdm2Conf
         fi
     else
         ## Update 3dm2.conf Logger setting to disable Logger
          $catPath $tdm2Conf | $grepPath -i 'Logger' >> /dev/null
          if [ $? -eq 0 ]; then
              $catPath $tdm2Conf | $grepPath 'Logger' | $cutPath -d ' ' -f2 | $grepPath '1' >> /dev/null
              if [ $? -eq 0 ]; then
                  $sedPath -i -e s/'Logger 1'/'Logger 0'/ $tdm2Conf
              fi
          else
              echo "Logger 0" >> $tdm2Conf
          fi
     fi

     ## Configure email to support logger
     if [ "$configMail" = "Y" ]; then
         configureEmail;

         ## Update 3dm2.conf EmailEnable setting
         $catPath $tdm2Conf | $grepPath 'EmailEnable' >> /dev/null
         if [ $? -eq 0 ]; then
             $catPath $tdm2Conf | $grepPath 'EmailEnable' | $cutPath -d ' ' -f2 | $grepPath '0' >> /dev/null
             if [ $? -eq 0 ]; then
                 $sedPath -i -e s/'EmailEnable 0'/'EmailEnable 1'/ $tdm2Conf
             fi
         else
             echo "EmailEnable 1" >> $tdm2Conf
         fi

         ## Update 3dm2.conf EmailServer setting
         $catPath $tdm2Conf | $grepPath 'EmailServer' >> /dev/null
         if [ $? -eq 0 ]; then
             curSetting=`$catPath $tdm2Conf | $grepPath 'EmailServer' | $cutPath -d ' ' -f2` >> /dev/null
             if [ "$curSetting" != "" ]; then
                 $sedPath -i -e s/'EmailServer $curSetting'/'EmailServer '$EmailServer/ $tdm2Conf
             else
                 $sedPath -i -e s/'EmailServer '/'EmailServer '$EmailServer/ $tdm2Conf
             fi
         else
             echo "EmailServer $EmailServer" >> $tdm2Conf
         fi

         ## Update 3dm2.conf EmailSender setting
         $catPath $tdm2Conf | $grepPath 'EmailSender' >> /dev/null
         if [ $? -eq 0 ]; then
             curSetting=`$catPath $tdm2Conf | $grepPath 'EmailSender' | $cutPath -d ' ' -f2` >> /dev/null
             if [ "$curSetting" != "" ]; then
                 $sedPath -i -e s/'EmailSender $curSetting'/'EmailSender '$EmailSender/ $tdm2Conf
             else
                 $sedPath -i -e s/'EmailSender'/'EmailSender '$EmailSender/ $tdm2Conf
             fi
         else
             echo "EmailSender $EmailSender" >> $tdm2Conf
         fi
         
         ## Update 3dm2.conf EmailRecipient setting
         $catPath $tdm2Conf | $grepPath 'EmailRecipient' >> /dev/null
         if [ $? -eq 0 ]; then
             curSetting=`$catPath $tdm2Conf | $grepPath 'EmailRecipient' | $cutPath -d ' ' -f2` >> /dev/null
             if [ "$curSetting" != "" ]; then
                 $sedPath -i -e s/'EmailRecipient $curSetting'/'EmailRecipient '$EmailRecipient/ $tdm2Conf
             else
                 $sedPath -i -e s/'EmailRecipient'/'EmailRecipient '$EmailRecipient/ $tdm2Conf
             fi
         else
             echo "EmailRecipient $EmailRecipient" >> $tdm2Conf
         fi
     fi

     ## Start 3dm2.
     ps ax | $grepPath -i '3dm2' | $grepPath -v 'grep' >> /dev/null
     if [ $? -eq 0 ]; then
         if [ -e /etc/rc.d/tdm2 ]; then
             if [ "$function" = "0" ]; then
                 echo ""
                 echo "*** Restarting 3DM2 using configuration found in $tdm2Conf ***"
             elif [ "$function" = "1" ]; then
                   echo ""
                   echo "*** Restarting 3ware Logger using configuration found in $tdm2Conf ***"
             fi
             ## Restart 3DM2 Daemon
             /etc/rc.d/tdm2 restart
             if [ $? -ne 0 ]; then
                 echo ""
                 echo "Failed to restart 3DM2."
                 echo ""
                 echo "You may need to reboot or restart the service manually to load new configuration."
             fi
         else
             echo ""
             echo "/etc/rc.d/tdm2 missing, you will need to restart 3DM2 manually."
         fi
     else
         if [ -e /etc/rc.d/tdm2 ]; then
             if [ "$function" = "0" ]; then
                 echo ""
                 echo "*** Starting 3DM2 using configuration found in $tdm2Conf ***"
             elif [ "$function" = "1" ]; then
                   echo ""
                   echo "*** Starting 3ware Logger using configuration found in $tdm2Conf ***"
             fi
             ## Start 3DM2 Daemon
             /etc/rc.d/tdm2 start
             if [ $? -ne 0 ]; then
                 echo ""
                 echo "Failed to start 3DM2."
                 echo ""
                 echo "You may need to reboot or start the service manually to load new configuration."
             fi
         else
             echo ""
             echo "/etc/rc.d/tdm2 missing, you will need to restart 3DM2 manually."
         fi
     fi

     echo ""
     echo "Cleaning up installation files...."
     echo ""
     sleep 3

     ## Clean up installation files from /tmp/3ware.
     cd /tmp
     if [ -d 3ware ]; then
         echo "Removing working directory /tmp/3ware"
         $rmPath -rfv ./3ware
     fi

     if [ "$optPrompt" = "Y" ]; then
         ## Display finish prompt to keep terminal open during install from CD menu
         echo ""
         read -p "Installation complete, press 'Enter Key' to continue. " waitExit
     fi
}
#End functions

## main()
## See how we were called
if [ "$optSelect" = "-i" ]; then
    if [ "$optPrompt" = "Y" ]; then
        showLicense;
    fi
    clear
    echo ""
    echo "3ware CLI & 3DM2 installation, configuration and removal script."
    echo "(c) 2010 LSI, Inc. All rights reserved."
    echo ""
    echo "Script version: "$scriptVer
    echo "*******************************"
    checkOld3dm2;
    checkOldConfig;
    checkLogger;
    setupInstall;
    doInstall;
    doConfig;
    doFinish;

elif [ "$optSelect" = "-u" ]; then
      doUninstall;

else
    doUsage;
fi
