#!/bin/bash -e

mkdir -p node
pushd node

config=`../bin/config.guess`
if [[ $config == *linux* ]]; then
    platform=linux
elif [[ $config == *darwin* ]]; then
    platform=darwin
else
    echo "Unknown platform ${config}!"
    exit 1
fi


function get_from_package {
    python << EOF
import json
with open('../package.json') as f:
    out = json.load(f).get('engines', {}).get('$1', '')
print(out)
EOF
}

nodeversion=$(get_from_package node)
yarnversion=$(get_from_package yarn)

nodefile="../requirements/node-v${nodeversion}-${platform}-x64.tar.xz"
yarnfile="../requirements/yarn-v${yarnversion}.tar.gz"

if [ ! -f $nodefile ]; then
    echo "Downloading node $nodeversion..."
    curl -L \
        "https://nodejs.org/download/release/v${nodeversion}/node-v${nodeversion}-${platform}-x64.tar.xz" \
        -o $nodefile &> /dev/null
fi

if [ ! -f $yarnfile ]; then
    echo "Downloading yarn $yarnversion..."
    curl -L \
        "https://github.com/yarnpkg/yarn/releases/download/v${yarnversion}/yarn-v${yarnversion}.tar.gz" \
        -o $yarnfile &> /dev/null
fi

rm -rf ../node/*
echo "Unpacking node..."
tar --strip-components=1 -Jxf ${nodefile}
echo "Unpacking yarn..."
tar --strip-components=1 -xzf ${yarnfile}

popd
