#!/bin/sh
#
# RETURN CODE:
#
#		0 Some Patch are install
#		1 No Patch to install
#		2 Cannot build the Kernel
#		3 Problem in the patch installation
# 		4 MiniRoot Patches to be install by the user and some Some Patch are install
# 		5 MiniRoot Patches to be install by the user and No Patch are install


kernel_check () {
	echo -n "Checking if kernel links ($1)..." 
	if { /etc/autoconfig -v 1>> ${FILE_KERNEL_ERROR} 2>&1; } then
		echo "Done"
	else
		echo ""
		echo "********************************************************"
		echo "YOUR IRIX KERNEL DOES NOT BUILD CORRECTLY"
		echo "THIS PROBLEM MUST BE FIXED BEFORE CONTINUING...."
		if [ -n ${MANUALPATCHES:-""} ]; then
			echo "You MAY need to install manually the following "
			echo "PATCHES: ${MANUALPATCHES}"
			echo "from the ${MANUALDIST} directory"
			echo "Please read carefully the release notes to"
			echo "know how to install theses and verify if theses patches apply to you"
		fi	
		echo "HERE ARE THE ERROR MESSAGES";
		cat ${FILE_KERNEL_ERROR};
		echo "********************************************************"
		exit 2;
	fi
	return 0;
}

check_for_patch () {
	DISTPATH=$1
        
        echo check_for_patch dist is $DISTPATH
        if [ ${#DISTPATH} -eq 0 ]; then
           echo "No Patch found in distribution"
           NOCONFLICT="No conflicts"
           return 0;
        fi
        
	echo "Checking for Patches to install in $1"
	echo "install patch installable" > ${FILE_INST_CMD}
	echo "keep patch downgrade"     >> ${FILE_INST_CMD}
	echo "keep same"		>> ${FILE_INST_CMD}
	echo "list install"		>> ${FILE_INST_CMD}
	echo "conflicts"		>> ${FILE_INST_CMD}
	echo "quit"			>> ${FILE_INST_CMD}

	PATCHES="";
	NOCONFLICT="";
	PATCHES_INDIR="";

	for DIRECTORY in ${DISTPATH};
	do

          # check if a patch list file exists
          if [ -e  ${DIRECTORY}/${CURRENT_PLATFORM}.list ]; then
            # New scheme, patches for all platforms are included.
            # We have to select the proper patches by reading the
            # the patch list and creating symbolic link in a 
            # platform sub-folder
            PLATFORM_PATCH_DIR=/tmp/.installpatch.links.$$ 
	
            # Clean directory and re-create it
            rm -rf ${PLATFORM_PATCH_DIR}
            mkdir -p  ${PLATFORM_PATCH_DIR}
    
            # read <platform>.list file
            PATCHLIST=`cat ${DIRECTORY}/${CURRENT_PLATFORM}.list`
 
            # for every patch listed in the file, 
            # create a symbolic link in a subdirectory
            # for this platform. 
            for PATCHNUMBER in ${PATCHLIST};
            do 
              # Convert our patch numbers (patch_xxxx or patch_yyyy_betaz)
              # into a sgi patch number SG000xxxx.
	      PATCHNUMBER=`echo $PATCHNUMBER | cut -d'_' -f2 | nawk '{printf "patchSG%07d\n",$1;}'`

              if [ -e ${DIRECTORY}/${PATCHNUMBER} ];then
                ln -s ${DIRECTORY}/${PATCHNUMBER}* ${PLATFORM_PATCH_DIR}
	      else
                echo "Error: Could not find patch ${PATCHNUMBER}"
              fi
            done

            # We will now look in the subdirectory instead
            DIRECTORY=${PLATFORM_PATCH_DIR}
          fi

          # Now check those patches finally.
	  inst -Vinteractive:false -Vverbosity:0 -n -f  ${DIRECTORY} < ${FILE_INST_CMD} 1> ${FILE_PATCH_LIST} 2> ${FILE_ERROR}

	  LOCALPATCHES="`grep '^i' ${FILE_PATCH_LIST} | cut -c 16-19| sort|uniq`"
	  LOCALPATCHES=${LOCALPATCHES}"`grep '^Inst> i' ${FILE_PATCH_LIST} | cut -c 22-25| sort|uniq`"

	  NOCONFLICT=${NOCONFLICT}"`grep -i 'No conflicts' ${FILE_PATCH_LIST}`"

	  if [ -n ${LOCALPATCHES:-""} ]; then
	    PATCHES=${PATCHES}${LOCALPATCHES};
	    PATCHES_INDIR="${PATCHES_INDIR} ${DIRECTORY}"
 	  fi

	  ERRORS=`grep ERROR ${FILE_PATCH_LIST}`
          if [ ${#ERRORS} != 0 ]; then
            echo "Error with selected patches"
            cat ${FILE_PATCH_LIST}
	    cat ${FILE_ERROR}
          fi
          
	done
	return 0;
}

check_for_conflict () {
	if [ -z ${NOCONFLICT:-""} ]; then
		echo "Problem with selected patch"
		cat ${FILE_PATCH_LIST}
		cat ${FILE_ERROR}
		exit 3
	fi
}

install_patches () {
	DISTPATH=$1;

        echo install_patches dist is $DISTPATH
        if [ ${#DISTPATH} -eq 0 ]; then
           echo "No Patch to install"
           return 0;
        fi
        
	echo "**Installing patches from $1: $PATCHES"
	echo "install patch installable" > ${FILE_INST_CMD}
	echo "keep patch downgrade"     >> ${FILE_INST_CMD}
	echo "keep same"		>> ${FILE_INST_CMD}
	echo "go"			>> ${FILE_INST_CMD}
	echo "quit"			>> ${FILE_INST_CMD}

	for DIRECTORY in ${DISTPATH};
	do
          # check if patches are in a platform subdirectory
          # (new scheme, patches for all platforms)
          if [ -d  ${DIRECTORY}/${CURRENT_PLATFORM} ]; then
            # We will now look in the subdirectory instead
            DIRECTORY=${DIRECTORY}/${CURRENT_PLATFORM}
          fi

	  inst -Vinteractive:false -Vverbosity:2 -f ${DIRECTORY} -Vmenus:off < ${FILE_INST_CMD}  2> ${FILE_ERROR} |tee -a ${FILE_ERROR}

	  ERRORS=`grep ERROR ${FILE_PATCH_LIST}`
          if [ ${#ERRORS} != 0 ]; then
            echo "Error installing some patches"
            cat ${FILE_PATCH_LIST}
	    cat ${FILE_ERROR}
          fi

	done
}

check_for_special () {
	MANUALDIST=${DISTRIBUTION}/$1
	if [ -d ${MANUALDIST} ]; then
		check_for_patch ${MANUALDIST}
		MANUALPATCHES=${PATCHES}
	fi
}

#
# Begin of the "Main"
#

# Some variables for temporary files...
FILE_PATCH_LIST=/tmp/.installpatch.list.$$
FILE_INST_CMD=/tmp/.installpatch.instcmd.$$
FILE_ERROR=/tmp/.installpatch.error.$$
FILE_KERNEL_ERROR=/tmp/.installpatch.kernelerror.$$


#
# Prepare for distributions directory
#
DISTRIBUTION=${1:-.};
if [ $DISTRIBUTION = "KERNEL_CHECK_ONLY" ]; then
	kernel_check "Before installing anything"
	exit 0;
fi

PATCH_OS_VERSION=`uname -R | cut -d' ' -f2  | sed 's/ //g'`
if [ -d ${DISTRIBUTION}/Patches/${PATCH_OS_VERSION} ]; then
  # New scheme, patches in a sub-directory for the os version.
  DISTRIBUTION=${DISTRIBUTION}/Patches/${PATCH_OS_VERSION}
else
  DISTRIBUTION=${DISTRIBUTION}/Patches
fi


#
# Figure out running platform
#
GRAPHICS=`hinv -c graphics|sort|uniq`
GRAPHICS_VPRO=`echo $GRAPHICS | grep "Graphics board: V1"`
BOARD_ONYX350=`hinv -c processor -m | grep 2U_INT_53`
IPNUM=`uname -m`
case $IPNUM in
  IP32)
    echo "Platform $IPNUM is NOT supported"
    exit -1
    ;;

  IP27)
    CURRENT_PLATFORM="onyx2"
    ;;

  IP30)
    if [ ${#GRAPHICS_VPRO} != 0 ]; then
      CURRENT_PLATFORM="octane2"
    else
      CURRENT_PLATFORM="octane"
    fi
    ;;

  IP35)
    if [ ${#GRAPHICS_VPRO} != 0 ]; then
      CURRENT_PLATFORM="tezro"
    else
      if [ ${#BOARD_ONYX350} != 0 ]; then
        CURRENT_PLATFORM="onyx350"
      else
        CURRENT_PLATFORM="onyx3"
      fi
    fi
    ;;

  *) 
    echo "ERROR unknown platform: $IPNUM"
    CURRENT_PLATFORM="unknown"
    ;;

esac


if [ -d ${DISTRIBUTION}/normal ]; then
	REGDIST=${DISTRIBUTION}/normal;
fi

#
# Check for NFS Package
#

NFS=`showprods -D 1 -s nfs`
if [ ${NFS:-""} = "" ]; then
	:
elif [ -d ${DISTRIBUTION}/nfs ]; then
        REGDIST="${REGDIST} ${DISTRIBUTION}/nfs"
fi

# Check if we have "Special care Patch to install"
check_for_special miniroot

# Check if we have Patch to install
check_for_patch "${REGDIST}"

# Check fo conflict
check_for_conflict

#
# Check if we have patches to instalL
#
if [ -z ${PATCHES:-""} ]; then
	RETURN_STATUS=1;
else 
	install_patches "${PATCHES_INDIR}"
	check_for_special miniroot
	kernel_check "After Installing Patches"
	RETURN_STATUS=0;
fi

#
# Check if we have some MANUALPATCH to install
#

if [ -n ${MANUALPATCHES:-""} ]; then
   echo "********************************************************"
	echo "The major part of the SGI PATCHES are installed"
	echo "However the following patches maybe also recommended:"
	echo "${MANUALPATCHES}, You will find theses in the"
	echo "${MANUALDIST} directory"
	echo "Please read the release notes carefully to"
	echo "know how to install these and verify if they patches apply to you"
	echo "The install program will continue Now..."
	echo "********************************************************"
	RETURN_STATUS=`expr $RETURN_STATUS + 4`
fi

# Cleanup
rm -rf ${PLATFORM_PATCH_DIR}

exit ${RETURN_STATUS}
