#!/bin/sh -ex

# Origin: http://download.openvz.org/utils/vzctl/
TARBALL=vzctl-3.0.26.2.tar.bz2

# ISSUE: Allow use inside "FROM"?  ISSUE: Verify that the current working
# directory is empty (or maybe that it already contains "tile-build")?

FROM=$(dirname $0)

# Copy "tile-build".
cp $FROM/tile-build .

# Identify all patches.
if [ -z "$PATCHES" ]; then
    PATCHES=$(ls $FROM | grep '[.]patch$' | sort || true)
fi

# Analyze the tarball.
case $TARBALL in *.tar.bz2) TARFLAG=-j ;; *) TARFLAG=-z ;; esac

# 'tar' changed the flag from '--strip-path' to --strip-components',
# so we have to use the appropriate one for the host version of 'tar'.
if tar --strip-path=1 --version > /dev/null 2>&1; then
    tar --strip-path=${TARDEPTH:-1} $TARFLAG -xf $FROM/$TARBALL
else
    tar --strip-components=${TARDEPTH:-1} $TARFLAG -xf $FROM/$TARBALL
fi

# Apply all patches.
for patch in $PATCHES; do
    : $patch
    patch -p1 < $FROM/$patch
done

# A helpful function.
function update_config_files ()
{
    for name in config.guess config.sub; do
        for path in `find . -name $name`; do
            cp -f $TILERA_ROOT/etc/$name $path
        done
    done
}

update_config_files
