#!/bin/sh

set -e

# This script automatically builds a Conda package

cd "$(dirname "$0")/../../.."
VT_DIR="$(pwd)"

# Clears Conda cache
ANACONDA_CACHE="$(dirname "$(which python)")/../conda-bld/src_cache/vistrails.tar.gz"
rm -f "$ANACONDA_CACHE"

if [ -z "$1" ]; then
    echo "Usage: $(basename $0) <target_directory> [version]" >&2
    exit 1
fi
if [ -z "$2" ]; then
    # describe gives us something like:
    # "v2.1.4", "v2.1.4-40-g1234567", "v2.2-pre-g1234567", "v2.2.0-rc1", "v2.2-rc2-g1234567"
    # note: no 'sed -r' on OS X
    VERSION="$(git describe --always --tags | sed 's/^v//' | sed 's/-g\([a-z0-9]*\)$//' | sed 's/-/./g')"
else
    VERSION="$2"
fi

DEST_DIR="$1"

TEMP_DIR=$(mktemp -d /tmp/vt_conda_XXXXXXXX)

# Builds source distribution
if ! python setup.py sdist --dist-dir $TEMP_DIR; then
    rm -Rf $TEMP_DIR
    exit 1
fi

# Creates symlink
TEMP_FILE="$(echo $TEMP_DIR/*)"
ln -s "$TEMP_FILE" $TEMP_DIR/vistrails.tar.gz

# Copies conda recipe
cp -r scripts/dist/conda/vistrails $TEMP_DIR/vistrails

sedi(){
    TEMPFILE=$(mktemp /tmp/vt_conda_XXXXXXXX)
    sed "$1" "$2" > $TEMPFILE
    mv $TEMPFILE "$2"
}

absolutepathname(){
    mkdir -p "$(dirname "$1")"
    cd "$(dirname "$1")"
    echo "$(pwd)/$(basename "$1")"
}

# Changes version in recipe
VERSION_ESCAPED="$(echo "$VERSION" | sed 's/\\/\\\\/g' | sed 's/\//\\\//g')"
sedi "s/_REPLACE_version_REPLACE_/$VERSION_ESCAPED/g" $TEMP_DIR/vistrails/meta.yaml

# Changes URL
URL_ESCAPED="$(echo "file://$TEMP_DIR/vistrails.tar.gz" | sed 's/\\/\\\\/g' | sed 's/\//\\\//g')"
sedi "s/_REPLACE_url_REPLACE_/$URL_ESCAPED/g" $TEMP_DIR/vistrails/meta.yaml

# Builds Conda package
cd $TEMP_DIR
OUTPUT_PKG="$(conda build --output vistrails)"
OUTPUT_PKG="$(absolutepathname "$OUTPUT_PKG")"
if ! conda build vistrails; then
    rm -Rf $TEMP_DIR
    rm -f "$ANACONDA_CACHE"
    exit 1
fi

# Copies result out
cd "$VT_DIR"
cp "$OUTPUT_PKG" "$DEST_DIR/"

# Removes temporary directory
rm -Rf $TEMP_DIR

# Clears Conda cache
rm -f "$ANACONDA_CACHE"
