#!/bin/bash
#
# build-server.sh
#
# Copyright (C) 2011-2012 Cesnet z.s.p.o
#
# Use of this source is governed by a BSD-style license, see LICENSE file.

VERSION="2.2"

err()
{
  echo "FAILED!"
  cat "$err"
  rm -f "$err" "$tar" "$sig"
  rm -rf "$package"
  echo
  echo "Build of $package package FAILED!!!"
  exit 1
}


#-------------------------------------------------------------------------------
#				MAIN
#-------------------------------------------------------------------------------

if [ -z "$1" ]; then
	echo "Usage: ${0##*/} <package_version_number>"
	echo
	echo "Example: ${0##*/} \"2.2\""
	exit 1
fi

package_name="warden-server"
package="${package_name}-$1"
bin="${package}/bin"
doc="${package}/doc"
etc="${package}/etc"
lib="${package}/lib"
sh="${package}/sh"
tar="${package}.tar.gz"
sig="${tar}.sig"
err="/tmp/${package}-err"

# make directory structure
echo "Building $package package..."
echo

echo -n "Building 'base' directory ... "
mkdir -p "$package" 2> "$err" || err
cp "../src/${package_name}/sh/install.sh" "$package" 2> "$err" || err
cp "../src/${package_name}/sh/update.sh" "$package" 2> "$err" || err
cp "../src/${package_name}/doc/INSTALL" "$package" 2> "$err" || err
cp "../src/${package_name}/doc/README" "$package" 2> "$err" || err
cp "../src/${package_name}/doc/UPDATE" "$package" 2> "$err" || err
echo "OK"

echo -n "Building '${bin}' directory ... "
mkdir -p "$bin" 2> "$err" || err
cp -R "../src/${package_name}/bin/"* "$bin" 2> "$err" || err
echo "OK"

echo -n "Building '${doc}' directory ... "
mkdir -p "$doc" 2> "$err" || err
cp -R "../src/${package_name}/doc/"* "$doc" 2> "$err" || err
echo "OK"

echo -n "Building '${etc}' directory ... "
mkdir -p "$etc" 2> "$err" || err
cp "../src/${package_name}/etc/"* "$etc" 2> "$err" || err
rm -f "${etc}/"*.conf 2> "$err" || err
echo "OK"

echo -n "Building '${lib}' directory ... "
mkdir -p "$lib" 2> "$err" || err
cp -R "../src/${package_name}/lib/"* "$lib" 2> "$err" || err
rm -f "${lib}/"*.t 2> "$err" || err
echo "OK"

echo -n "Building '${sh}' directory ... "
mkdir -p "$sh" 2> "$err" || err
cp "../src/${package_name}/sh/uninstall.sh" "$sh" 2> "$err" || err
echo "OK"

echo -n "Creating MANIFEST file ... "
cd "$package" && find . -mindepth 2 -type f | sed 's/.tmpl//' | sed 's/.\///' > "doc/MANIFEST" && cd $OLDPWD || err
echo "OK"


# create tarball
echo -n "Creating $tar tarball ... "
tar czf "$tar" "$package" 2> "$err" || err
echo "OK"


#  create sign of tarball
echo -n "Creating $sig file ... "
sha1sum "$tar" > "$sig" 2> "$err" || err
echo "OK"


echo
echo "Building of $package package was SUCCESSFULL!!!"

# cleanup section
rm -rf "$package" "$err"

exit 0
