#!/bin/sh
# Version 0.1 - unlikely to be further updated!
# See readme.txt for usage and sample output.
# Tested with Solaris 10 Update 6.
# (c) Steve Parker 2009
# http://steve-parker.org/code/sh/getcluster/
# GPL Version 2 (not v3).

# Get Solaris packages' clusters
# Looks for a .clustertoc file in: clustertoc .clustertoc /cdrom/cdrom0/Solaris*/Product/.clustertoc /cdrom/Solaris*/Product/.clustertoc /mnt/Solaris*/Product/.clustertoc c

PKG=$1

if [ -z "$PKG" ]; then
  echo "Usage: `basename $0` packagename"
  echo " This is a tool match Solaris installation clusters to packages."
  exit 1
fi

#############################################################################
# Pick up GNU grep if we can:
PATH=/usr/sfw/bin:$PATH
export PATH
type ggrep >/dev/null 2>&1
if [ "$?" -eq "0" ]; then
  GREP=`which ggrep`
else
  GREP=`which grep`
fi

echo foo |$GREP -A2 bar > /dev/null 2>&1
HAVEGNUGREP=$?
# 1 for GNU (not found); 2 for Solaris (invalid syntax)
#############################################################################

CLUSTERTOC=`ls clustertoc .clustertoc /cdrom/cdrom0/Solaris*/Product/.clustertoc /cdrom/Solaris*/Product/.clustertoc /mnt/Solaris*/Product/.clustertoc 2>/dev/null|head -1`
if [ ! -f "${CLUSTERTOC}" ]; then
  echo "Cannot find a ClusterTOC"
  exit 1
fi

# There should only be one match, but only take the first anyway
linenum=`$GREP -n "^SUNW_CSRMEMBER=${PKG}$" $CLUSTERTOC|cut -d":" -f1|head -1`
if [ -z "$linenum" ]; then
  echo "Package $PKG not found in $CLUSTERTOC"
  echo
  # PKG may be "-?" or "-h" etc...
  echo "Usage: `basename $0` packagename"
  echo " This is a tool to search Solaris install media for Clusters and MetaClusters providing packages."
  exit 1
  exit 1
fi

CLUSTER=`head -${linenum} $CLUSTERTOC | $GREP "^CLUSTER="|cut -d"=" -f2-|tail -1`
echo $PKG is in cluster $CLUSTER
if [ "$HAVEGNUGREP" -eq "1" ]; then 
  head -${linenum} $CLUSTERTOC |$GREP -A4 "^CLUSTER="|cut -d"=" -f2-|tail -4
fi

echo
echo "=> Installation Cluster(s):"
echo
lines=`$GREP -n "^SUNW_CSRMEMBER=${CLUSTER}$" $CLUSTERTOC |cut -d":" -f1`
for i in $lines
do
  if [ "$HAVEGNUGREP" -eq "1" ]; then 
    head -${i} $CLUSTERTOC | $GREP -A2 "^METACLUSTER=" | tail -3|cut -d"=" -f2-
    echo
  else
    head -${i} $CLUSTERTOC | $GREP "^METACLUSTER=" | tail -1 |cut -d"=" -f2-
  fi
done
