#!/bin/bash
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL
# the script will regenerate the apt database like this:
# genbasedir --flat --bloat /opt/apt/ core updates drbl
# genbasedir --hashonly /opt/apt/ core updates drbl

paramno="$#"
APTDIR="$1"
shift
MOD="$@"
MOD_ALL=""

USAGE="Usage: $0 APTDIR PACKAGE"

if [ "$paramno" -lt 1 ]; then
  echo "$USAGE"
  echo "If PACKAGE is ommited, package will be searched automatically."
  echo "Note! APTDIR must be absolute path!"
  echo "Example: "
  echo "$0 /opt/apt core updates drbl OOo"
  echo "where RPMS.core, RPMS.updates, RPMS.drbl and RPMS.OOo exist in /opt/apt"
  exit 1
fi

# 
[ "$(dirname $APTDIR)" = "." ] && echo "\"$APTDIR\" is a relative path! You must provide absolute path for apt dir! Program terminated!" && exit 1

# try to find all the sorts.
for ipkg in $APTDIR/RPMS.*; do
  if [ -d "$ipkg" ]; then
    ipkg=$(basename ${ipkg})
    MOD_ALL="$MOD_ALL ${ipkg:5}"
  fi
done

#
if [ -d "$APTDIR" -a -z "$MOD" ]; then
   for ipkg in $APTDIR/RPMS.*; do
     if [ -d "$ipkg" ]; then
       ipkg=$(basename ${ipkg})
       MOD="$MOD ${ipkg:5}"
     fi
   done
fi
###########################################################################
#### $MOD packages for Redhat/Fedora/Mandrake
###########################################################################

# Regenerate the apt indexes
genbasedir --flat --bloat --bz2only --progress $APTDIR/ $MOD

####################################
########### Remake hash ############
####################################
# To save space, actually we do not need those unbzip2 srclist.*/pkglist.*,
# We use --bz2only when run genbasedir, we will bunzip2 the
# srclist.*.bz2 and pkglist.*.bz2 (while keep the original one) to let
# genbase --hashonly can create the srclist.*/pkglist.* (without bz2) checksum
# in base/release
(cd $APTDIR/base; bunzip2 -k pkglist.* srclist.*)

# rerun genbashdir --hashonly is necessary, because we might not run all modules# we might run some modules. This will make base/release contains those unbzip2 srclist.*/pkglist.*.
echo "Generating hash for $MOD_ALL..."
genbasedir --hashonly $APTDIR $MOD_ALL

# Comment this, since the base directory includes all files for urpmi and apt, we can not remove the bz2 files.
# clean those not bzip2 pkglist and srclist. we only need bzip2 ones.
# find $APTDIR/base -type f ! -name "pkglist.*.bz2" ! -name "srclist.*.bz2" ! -name "release*" -exec rm -f {} \;

echo "-----------------------------------------------------------------"
echo "If you want to use this apt repository in this machine,"
echo "add the following line to /etc/apt/sources.list"
echo "rpm copy:$APTDIR . $MOD"
echo "-----------------------------------------------------------------"
