#!/bin/bash

BUNDLE_VERSION=0.0.6

# Find the script dir, following one level of symlink.
if [ -L "$0" ] ; then
    SCRIPT_DIR=$(dirname $(readlink "$0") )
else
    SCRIPT_DIR=$(dirname "$0")
fi

# OS Check. Put here because here is where we download the precompiled
# bundles that are arch specific.
UNAME=$(uname)
if [ "$UNAME" != "Linux" -a "$UNAME" != "Darwin" ] ; then
    echo "Sorry, this OS is not supported."
    exit 1
fi

if [ "$UNAME" = "Darwin" ] ; then
    if [ "i386" != $(uname -p) -o "1" != $(sysctl -n hw.cpu64bit_capable 2>/dev/null || echo 0) ] ; then

        # Can't just test uname -m = x86_64, because Snow Leopard can
        # return other values.
        echo "Only 64-bit Intel processors are supported at this time."
    fi
elif [ "$UNAME" = "Linux" -a "x86_64" != $(uname -m) ] ; then
    echo "Only 64-bit Intel processors are supported at this time."
fi

function install_dev_bundle {
    set -e
    trap "echo Failed to install dependency kit." EXIT

    TARBALL="dev_bundle_${UNAME}_${BUNDLE_VERSION}.tar.gz"
    TMPDIR="$SCRIPT_DIR/dev_bundle.xxx"

    rm -rf "$TMPDIR"
    mkdir "$TMPDIR"

    if [ -f "$SCRIPT_DIR/$TARBALL" ] ; then
        echo "Skipping download and installing kit from $SCRIPT_DIR/$TARBALL"
        tar -xzf "$SCRIPT_DIR/$TARBALL" -C "$TMPDIR"
    else
        curl -# https://d3sqy0vbqsdhku.cloudfront.net/$TARBALL | tar -xzf - -C "$TMPDIR"
        test -x "${TMPDIR}/bin/node" # bomb out if it didn't work, eg no net
    fi

    mv "$TMPDIR" "$SCRIPT_DIR/dev_bundle"

    echo "Installed dependency kit v${BUNDLE_VERSION} in dev_bundle."
    echo

    trap - EXIT
    set +e
}


if [ -d "$SCRIPT_DIR/.git" ]; then
    # In a checkout.

    if [ ! -d "$SCRIPT_DIR/dev_bundle" ] ; then
        echo "It's the first time you've run Meteor from a git checkout."
        echo "I will download a kit containing all of Meteor's dependencies."
        install_dev_bundle
    elif [ ! -f "$SCRIPT_DIR/dev_bundle/.bundle_version.txt" ] ||
        grep -qvx "$BUNDLE_VERSION" "$SCRIPT_DIR/dev_bundle/.bundle_version.txt" ; then
        echo "Your dependency kit is out of date. I will download the new one."
        rm -rf "$SCRIPT_DIR/dev_bundle"
        install_dev_bundle
    fi

    DEV_BUNDLE="$SCRIPT_DIR/dev_bundle"
    METEOR="$SCRIPT_DIR/app/meteor/meteor.js"
else
    # In an install
    DEV_BUNDLE=$(dirname "$SCRIPT_DIR")
    METEOR="$DEV_BUNDLE/app/meteor/meteor.js"
fi

export NODE_PATH="$DEV_BUNDLE/lib/node_modules"
exec "$DEV_BUNDLE/bin/node" "$METEOR" "$@"
