#!/bin/ksh -p
#
# ident "@(#)utpreserve.ksh	1.6 05/05/02 SMI"
#
# Copyright 2004-2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

PATH=/bin:/usr/bin:/usr/sbin

PROGRAM_ID="${0##*/}"
PROGRAM_DIR="${0%/*}"

Usage() {
  print -u2 "Usage: $PROGRAM_ID $PROGRAM_OPTS"
  print -u2 ""
  print -u2 " -d data_dir  : specify a directory to store the data in"
  exit 1
}

Fatal() {
  print -u2 "$PROGRAM_ID: fatal, $1"
  exit 1
}

OPTSTR=":d:"
PROGRAM_OPTS="[-d data_dir]"

ARGS=""

while getopts $OPTSTR OPT; do
  case "$OPT" in
    d) ARGS="$ARGS -d $OPTARG";;
   \?) Usage;;
  esac
done
shift $(($OPTIND - 1))

if (( $# != 0 )); then
  Usage
fi

case "$(id)" in
  'uid=0('*) ;; # ok uid is zero (root)
  *) Fatal "must be run as 'root'";;
esac

TMP_DIR="/tmp/$PROGRAM_ID.$$"

rm -rf $TMP_DIR

mkdir -p $TMP_DIR/opt

OS="$(uname -s)"

case "$OS" in
SunOS)
  ISA="$(uname -m)"
  case "$ISA" in
  sun4*)
    PKG_DIR="$PROGRAM_DIR/Sun_Ray_Core_Services_3.1/Solaris_8+/sparc/Packages"
    ;;
  i?86*|i86*)
    PKG_DIR="$PROGRAM_DIR/Sun_Ray_Core_Services_3.1/Solaris_10+/i386/Packages"
    ;;
  esac
  cp $PROGRAM_DIR/.install/admin_default $TMP_DIR
  pkgadd -R $TMP_DIR -a $TMP_DIR/admin_default -d $PKG_DIR SUNWuti >/dev/null 2>&1
  ;;

Linux)
  PKG_DIR="$PROGRAM_DIR/Sun_Ray_Core_Services_3.1/Linux/Packages"
  mkdir -p $TMP_DIR/bin
  mkdir -p $TMP_DIR/var/lib/rpm
  PKGS_RPM="/var/lib/rpm/packages.rpm"
  if [[ -f $PKGS_RPM ]]; then
    ln -s $PKGS_RPM $TMP_DIR$PKGS_RPM
  fi
  rpm --root $TMP_DIR --initdb
  rpm --root $TMP_DIR --nodeps -i $PKG_DIR/SUNWuti-3.1-?*.i386.rpm
  ;;
esac

$TMP_DIR/opt/SUNWut/sbin/utpreserve $ARGS

rm -rf $TMP_DIR
#
# no need to 'pkgrm' or 'rmp -e' the SUNWuti pkg in TMP_DIR

exit 0
