#!/bin/sh
#
#  ________  ___       __   ___  ________
# |\   ____\|\  \     |\  \|\  \|\   ____\
# \ \  \___|\ \  \    \ \  \ \  \ \  \___|
#  \ \_____  \ \  \  __\ \  \ \  \ \  \  ___
#   \|____|\  \ \  \|\__\_\  \ \  \ \  \|\  \
#     ____\_\  \ \____________\ \__\ \_______\
#    |\_________\|____________|\|__|\|_______|
#    \|_________|

#    It's delicious.
#    Brought to you by the fine folks at Gilt (http://github.com/gilt)

args=$@

# Sourcing nvm is nuking our parameters on Red Hat linux (Jenkins) so I am going to store the params here.
command=$0
firstParam=$1
secondParam=$2

bold=$(tput bold)
underline=$(tput sgr 0 1)
reset=$(tput sgr0)

red=$(tput setaf 1)
gray=$(tput setaf 8)
white=$(tput setaf 7)

dir=`dirname $command`
bin=`perl -e "print readlink '$command'"`
binDir=`dirname $dir/$bin`
localSwigCliDir="./node_modules/@gilt-tech/swig"

swigDir=$binDir/..
if [ -f $localSwigCliDir/package.json ]; then
  swigDir=$localSwigCliDir
fi

pkg=$(cat $swigDir/package.json)

function version {
  prop='version'
  temp=`echo $pkg | sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep "$prop:" | cut -d":" -f2 | sed -e 's/^ *//g' -e 's/ *$//g' `
  echo ${temp##*|}
}

export SWIG_VERSION=`version`

#echo "·\n· ${bold}${white}hey guys! oh big gulps eh? - ${underline}${grey}http://youtu.be/praFGD51ih8${reset}\n·"
echo "  ·"
echo "  ·  ${red}swig${reset}         v$SWIG_VERSION"

# NVM is used here as a convenience and an assertion that we're using the right
# version of node. It's not required in production, as production should be using
# the right version of node natively.
if [ "$NODE_ENV" != "production" ]; then
  source $binDir/check_node_version
fi

if [ "$firstParam" == "init" ]; then
  node "$swigDir/lib/init.js" $secondParam
  # --use-yarn
  exit
fi

if [ "$firstParam" == "update" ]; then
  node "$swigDir/lib/update.js"
  exit
fi

if [ "$firstParam" == "pre-publish" ]; then
  node "$swigDir/lib/pre-publish" $args
  # --vendor
  # --less
  exit
fi

if [ "$firstParam" == "help" ]; then
  node "$swigDir/index.js" $firstParam "--task=$secondParam"
  exit
fi

# pass control to gulp
node "$swigDir/lib/update.js"
node "$swigDir/index.js" $args
