#!/usr/bin/env bash
#
# This script works with Debian 8 and Ubuntu 14.04 (LTS)
# Go seems to build poorly on Ubuntu 12.04 (LTS)

set -eux
trap 'echo FAIL' ERR

apt-get -y update
apt-get -y install binutils bison curl gcc git golang-go make
go_version=$(go version | sed 's/go version go//; s/ .*//')
if [[ $go_version < 1.3.1 ]]; then
  [[ -r ~/.gvm/scripts/gvm ]] ||
    bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)
  set +u
  source ~/.gvm/scripts/gvm
  gvm install go1.4.2
  gvm use go1.4.2
  set -u
fi

cd $(dirname ${BASH_SOURCE[0]})
if git rev-parse; then
  cd $(git rev-parse --show-toplevel)
elif [ -e bootstrap ];then
  cd ..
else
  cd /tmp
  [ -d git-lfs ] || git clone https://github.com/github/git-lfs
  cd git-lfs
fi

./script/bootstrap
install -D bin/git-lfs /usr/local/bin
git lfs init

apt-get -y install build-essential groff man
if grep -q Debian /etc/issue; then
  apt-get install -y ruby ruby-dev
elif grep -q Ubuntu /etc/issue; then
  apt-get -y install ruby2.0 ruby2.0-dev
  rm /usr/bin/ruby && sudo ln -s /usr/bin/ruby2.0 /usr/bin/ruby
  rm -fr /usr/bin/gem && sudo ln -s /usr/bin/gem2.0 /usr/bin/gem
else
  {
    echo "unknown Debian release"
    cat /etc/issue
  } >&2
  exit 1
fi

gem install ronn
./script/man
install -d /usr/local/share/man/man1
install man/*.1 /usr/local/share/man/man1
git help lfs > /dev/null

echo SUCCESS
