#! /bin/bash
# $Id: rpminst,v 1.10 1998/11/26 10:41:41 ray Exp ray $
# full fledged bash version (requires perl also!)
# (external: rpmextr, cpio, sleep + perl)
C=$0; C=${C##*/}

DOIT=
CpioP=
All=true
Verbose=false
Vlevel=0
Debug=false
Dlevel=0

Usage() {
  echo "Usage: $C [--force] [--verbose] [--spec] package.rpm ..." 1>&2
  exit 1
}
true() {
  return 0
}
false() {
  return 1
}

while [ $# -gt 0 ]; do
  case "X$1" in
   X--test|X-n)
    DOIT=echo
    shift
    ;;
   X--force|X-f)
    Cpio=${Cpio}u
    shift 
    ;;
  X--debug)
    Dlevel=$[ $Dlevel + 1 ]
    shift
    ;;
  X--verbose|X-v)
    Vlevel=$[ $Vlevel + 1 ]
    shift
    ;;
  X--spec|X-s)
    CpioP='*.spec' 
    All=false
    shift
    ;;
  X-*)
    Usage
    ;;
  X*)
    break
    ;;
  esac
done

# try to prepend path to this script to $PATH to find matching version
# of rpmextr
ADD=$0; ADD=${ADD%/*}
if [ -x $ADD/rpmextr ]; then
  [ -n $(perl -e '($_)=@ARGV;/^[^\/]/&&print;' $ADD) ] &&
    ADD=$(cd $ADD; pwd)
  if [ -n $(perl -e '($_,$p)=@ARGV;/(^|:)$p(:|$)/&&print;' $PATH $ADD) ]; then
    [ $Dlevel -gt 1 ] && echo "prepending '$ADD' to PATH"
    PATH=$ADD:$PATH
    export PATH
  fi
fi

[ $Vlevel -ge 1 ] && Cpio=${Cpio}v
[ $Vlevel -ge 2 ] && Verbose=true

#echo "C='$C'"
case "$C" in
 *inst*)
  Inst=true
  Cpio=dm$Cpio
  ;;
 *show*|*)
  Inst=false
  Cpio=tv
  ;;
esac

Process()
{
  local stage=$1
  local file=$2
  local name=$3
  local run=$4
  local script out

  $All || return 0

  out="%${stage}-${name}"
  script=$(rpmextr --tag=$stage $file)

  echo "$out"
  if [ -z "$script" ]; then
    echo "--empty--"
  else
    if $run; then
      echo "$script" | sh -x
    elif $Inst; then
      echo "$script"
      echo "$script" > $out
    else
      echo "$script"
    fi
  fi
  return $?
}

Run=false
if $Inst && $All && [ $(pwd) = "/" ]; then
  echo "pre- and post-install scripts will be executed..."
  sleep 4
  Run=true
fi

for P in "$@"; do
  name=${P##*/}; name=${name%.i386.rpm}

  if [ ! -f "$P" ] || [ ! -r "$P" ]; then
    echo "$C: can't read from '$P'! Skipped..." 1>&2
    continue
  fi

  $Verbose && echo "*** $P"
  Process prein $P $name $Run

  $Verbose && echo "%files-${name}"

  [ -n "$CpioP" ] && set -f
  set -- X $CpioP; shift

  rpmextr --cpio $P | cpio -i$Cpio "$@"

  [ -n "$CpioP" ] && set +f

  Process postin $P $name $Run

  Process preun $P $name false
  Process postun $P $name false

done

