#!/bin/bash -exu

HEREDIR=`dirname $0`
cd "$HEREDIR"
HEREDIR=`pwd`
cd ..
ROOTDIR=`pwd`

# Ensure imagemagick is installed
if which convert && convert 2>/dev/null | grep ImageMagick 
then
  echo "Congrats. You already have ImageMagick installed."
else
  if which brew 1>/dev/null 2>/dev/null
  then
    brew install imagemagick
  else
    if which apt-get 1>/dev/null 2>/dev/null
    then
      sudo apt-get install imagemagick
    fi
  fi
fi

# Ensure imagemagick is installed
if which gm && gm -help 2>/dev/null | grep GraphicsMagick 
then
  echo "Congrats. You already have GraphicsMagick installed."
else
  if which brew 1>/dev/null 2>/dev/null
  then
    brew install graphicsmagick
  else
    if which apt-get 1>/dev/null 2>/dev/null
    then
      sudo apt-get install graphicsmagick
    fi
  fi
fi

# Ensure unbuffer is installed
if which unbuffer 
then
  echo "Congrats. You already have Unbuffer installed."
else
  if which brew 1>/dev/null 2>/dev/null
  then
    brew install expect
  else
    if which apt-get 1>/dev/null 2>/dev/null
    then
      sudo apt-get install expect
    fi
  fi
fi

# Select XCode if you installed CommandLineTools afterwards
( hash xcode-select && sudo xcode-select -s /Applications/Xcode.app/Contents/Developer ) || echo "No XCode to be selecting"

# Install everything else
unset NODE_ENV
npm install
if which rbenv 
then 
  echo "Found rbenv already installed; using it"
else
  rm -r -f -v "$ROOTDIR/.rbenv"
  git clone https://github.com/rbenv/rbenv.git "$ROOTDIR/.rbenv"
  git clone https://github.com/rbenv/ruby-build.git "$ROOTDIR/.rbenv/plugins/ruby-build"
  cd "$ROOTDIR/.rbenv" 
  ( ./src/configure && make -C src ) || echo "Binary build of rbenv failed; no big deal. Things will just be slower."
  export PATH="$ROOTDIR/.rbenv/bin:$PATH"
fi
eval "$(rbenv init -)" # For good measure
cd "$ROOTDIR"
rbenv install -s -v
gem install bundler 
rbenv rehash 
bundle install --clean --force
rbenv rehash
cd "$ROOTDIR/src/elm"
bundle exec elm-install


