#!/bin/sh
# Retrieves RPMs from update media.
# Written by T.Nonogaki
APPVER=1.0
VERSION=$1
MODE=update
ME=$(basename $0)

## Variables. You can fiddle with them.
#
# Name of distribution. This should be the exact name of top directory
# where RPMS/ resides, in source media.
DIST=RedHat
# Absolute path of top of destination directory.
LOCALMIRRORDIR=/home/yumadm/pub/package
# Directory where original os packages will reside,
# relative to $LOCALMIRRORDIR/redhat/linux/$VERSION/en/os/i386/
OSDIR=$DIST/RPMS
# Directory where `base' files such as comps.xml reside.
BASE=$DIST/base
# Mount point of source media.
MOUNTP=/media/cdrom
# Source directory where to fetch packages from. If not empty,
# this overrides default RPMSOURCE, $MOUNTP/$DIST/RPMS.
# Example: RPMSOURCE=/var/cache/yum/updates-released/packages
RPMSOURCE=""
# Architectures you want to deal with.
ARCHS=(i386 i686 noarch)
# Definition of copy command.
COPY='cp -f -v'

function show_help() {
  cat <<EOF
$ME Ver$APPVER - Packge fetch utility for use with make-apt
USAGE:  $ME [VERSION] (MODE)
where VERSION is one of \`8', \`FC3', \`4ES' or something alike,
optional MODE is \`base', \`os' or \`update' which defaults to
\`update' if omitted.
EOF
}

## Argument handling

if [ -z "$VERSION" ]; then
  show_help
  exit 1
fi

case $1 in
  --help)
    show_help
    exit 1
    ;;
  -h)
    show_help
    exit 1
    ;;
esac

if [ $# -eq 2 ]; then
  case $2 in
    base)
      MODE=base;;
     os)
      MODE=os;;
  update)
      MODE=update;;
    *)
      show_help
      exit 1
      ;;
  esac
fi

## Fix variables.
if [ -z "$RPMSOURCE" ]; then
  if [ $MODE = base ]; then
    RPMSOURCE=$MOUNTP/$BASE
  else
    RPMSOURCE=$MOUNTP/$OSDIR
  fi
fi

case $MODE in
  base)
    DESTDIR=redhat/linux/$VERSION/en/os/i386/$BASE
    ;;
  os)
    DESTDIR=redhat/linux/$VERSION/en/os/i386/$OSDIR
    ;;
  *)
    DESTDIR=redhat/linux/updates/$VERSION/en/os
    ;;
esac

## Here we go.
if [ ! -d $RPMSOURCE ] ; then
  echo "Source: $MOUNTP not ready yet!"
  exit 1
fi

if [ ! -d $LOCALMIRRORDIR ] ; then
  echo "Top dir: $LOCALMIRRORDIR does not exist!"
  exit 1
fi

if [ ! -d $LOCALMIRRORDIR/$DESTDIR ]; then
  echo "Destination: $DESTDIR does not exist!"
  exit 1
fi

case $MODE in
  base)
    $COPY $RPMSOURCE/* $LOCALMIRRORDIR/$DESTDIR/
    ;;
   os)
    find $RPMSOURCE/ -type f ! -name "*.src.rpm" -name "*.rpm" -exec $COPY '{}' $LOCALMIRRORDIR/$DESTDIR/ \;
    ;;
   *)
    for i in ${ARCHS[@]}; do
      [ -d $LOCALMIRRORDIR/$DESTDIR/$i ] || mkdir $LOCALMIRRORDIR/$DESTDIR/$i
      find $RPMSOURCE/ -type f ! -name "*.src.rpm" -name "*.${i}.rpm" -exec $COPY '{}' $LOCALMIRRORDIR/$DESTDIR/$i/ \;
    done
    ;;
esac

exit 0
