#!/bin/sh

set -e

npm_version="$1"

if [ "$npm_version" == "" ]; then
  echo "usage: $0 VERSION"
  exit 1
fi

if [ "$AWS_ID" == "" ]; then
  echo "must set AWS_ID"
  exit 1
fi

if [ "$AWS_SECRET" == "" ]; then
  echo "must set AWS_SECRET"
  exit 1
fi

if [ "$S3_BUCKET" == "" ]; then
  echo "must set S3_BUCKET"
  exit 1
fi

basedir="$( cd -P "$( dirname "$0" )" && pwd )"

# make a temp directory
tempdir="$( mktemp -t node_XXXX )"
rm -rf $tempdir
mkdir -p $tempdir
cd $tempdir

# download npm
git clone https://github.com/isaacs/npm.git

# go into npm dir
pushd npm

# grab the right version
git checkout v${npm_version}
git submodule update --init --recursive

# package it up
tar czvf $tempdir/npm-${npm_version}.tgz *

# upload npm to s3
$basedir/aws/s3 put $S3_BUCKET \
  npm-${npm_version}.tgz $tempdir/npm-${npm_version}.tgz

# generate manifest
$basedir/manifest npm
