#! /bin/sh

# This script takes the compiled tarball, makes an RPM package and
# a patch against the latest released version, then uploads
# everything over ssh and removes old snapshots.
# Run this script in the directory where mc was built.

# TODO:
#  build tarball, select level of testing
#  (dist, distcheck, warning checks)


# $1 - file to upload, $2 - shell mask to erase
upload() {
  echo "Uploading $1 to $SITE"
  name="`basename $1`"
  scp "$1" "$SITE:$DIR/.in.$name"
  ssh $SITE "rm -f $DIR/$2; mv $DIR/.in.$name $DIR/$name"
}

set -e

# Version to make patches against.
# The source tree should be available in uncompressed form
BASE_VERSION="4.6.1"

# Version of the snapshot
MCVERSION=`date "+%Y-%m-%d-%H" --utc`

# Local directories
MC_BASE_DIR="$HOME/src/mc-$BASE_VERSION"
MC_CVS_DIR="$HOME/src/mc"
MC_BUILD_DIR="$HOME/src/mc.snap"
RPM_SRC_DIR="$MC_BUILD_DIR/rpm"

# Location of the snapshot directory
SITE="login.ibiblio.org"
DIR="/public/ftp/pub/Linux/utils/file/managers/mc/snapshots"
# DIR="/public/html/mc/snapshots"

# Command for building RPM
RPMBUILD=lsb-rpm

cd "$MC_CVS_DIR"
cvs up -dPA
test -d "$MC_BUILD_DIR" && chmod -R u+rwx "$MC_BUILD_DIR"
rm -rf "$MC_BUILD_DIR"
cp -a "$MC_CVS_DIR" "$MC_BUILD_DIR"
cd "$MC_BUILD_DIR"

# Sanity check
if ! test -f ./autogen.sh || ! test -f src/screen.c; then
  echo "Not in the MC CVS working directory"
  exit 1
fi

# Remove old tarballs and build the new one
rm -f "mc*.tar.gz"
cp -f configure.ac configure.ac.cvs
sed "s/AM_INIT_AUTOMAKE([^)]*)/AM_INIT_AUTOMAKE(mc, $MCVERSION)/" \
  configure.ac.cvs >configure.ac
./autogen.sh
make all
make distcheck

# Make sure that the new tarball exists
MCTARBALL="mc-$MCVERSION.tar.gz"
if test ! -f "$MCTARBALL"; then
  echo "No tarball found!!!"
  exit 1
fi

# Make an RPM package
rm -rf $RPM_SRC_DIR
mkdir "$RPM_SRC_DIR"
mkdir "$RPM_SRC_DIR/BUILD"
mkdir "$RPM_SRC_DIR/RPMS"
mkdir "$RPM_SRC_DIR/RPMS/i386"
mkdir "$RPM_SRC_DIR/SPECS"
$RPMBUILD -tb --define="_topdir $RPM_SRC_DIR" \
  "$MCTARBALL"
MC_RPM_VERSION=`echo $MCVERSION | sed s/-//g`
MC_RPM=$RPM_SRC_DIR/RPMS/i386/mc-$MC_RPM_VERSION-1.i386.rpm
if test ! -f $MC_RPM; then
  echo "Failed to compile package!!!"
  exit 1
fi

# Make a patch against the latest released version
MC_PATCH="mc-$BASE_VERSION-$MCVERSION.diff"
MC_PATCH_BZ2="$MC_PATCH.bz2"
if test ! -d $MC_BASE_DIR; then
  echo "Cannot find unpacked base version!!!"
  exit 1
fi
rm -f $MC_PATCH $MC_PATCH_BZ2
rm -rf mc-$MCVERSION
gzip -cd $MCTARBALL | tar xf -

# GNU diff should return 0 or 1.  2 means failure or incomplete diff.
diff -urN -x '*.gmo' -x pc $MC_BASE_DIR mc-$MCVERSION/ >$MC_PATCH || test $? = 1
bzip2 $MC_PATCH

upload "$MCTARBALL" "mc*.tar.gz"
upload "$MC_RPM" "mc*.i386.rpm"
upload "$MC_PATCH_BZ2" "mc*.diff.bz2"

echo "Done"
