#!/bin/sh


yum -y install git dmidecode
BOLD=`tput bold`
NORM=`tput sgr0`
CHEF_CLIENT_VERSION="18.5.0"
if [ "$MU_BRANCH" == "" ];then
  MU_BRANCH="master"
  mydir="`dirname $0`"
  cd $mydir
  if git rev-parse --abbrev-ref HEAD > /dev/null 2>&1;then
    MU_BRANCH="`git rev-parse --abbrev-ref HEAD`"
  fi
fi

# XXX All RHEL family. We can at least cover Debian-flavored hosts too, I bet.
DIST_VERSION=`rpm -qa \*-release\* | grep -Ei "redhat|^centos" | cut -d"-" -f3`
#IS_AMAZON=0
if [ "$DIST_VERSION" == "" ];then # funny package name in Amazon Linux
  DIST_VERSION=6
#  IS_AMAZON=1
elif [ "$DIST_VERSION" == "server" ];then # funny package name in RHEL6
  DIST_VERSION="6"
fi

if [ "$DIST_VERSION" == 7 ];then
  CHEF_CLIENT_PKG="chef-$CHEF_CLIENT_VERSION.el7.x86_64"
else
  CHEF_CLIENT_PKG="chef-$CHEF_CLIENT_VERSION.el6.x86_64"
fi


if ! /bin/rpm -q curl > /dev/null ;then
  /usr/bin/yum -y install curl
fi
if [ ! -f /opt/chef/bin/chef-apply ];then
  if /bin/rpm -q $CHEF_CLIENT_PKG > /dev/null ;then
    /usr/bin/yum -y erase chef || /bin/rpm -e chef
  fi
fi
set -x
set -e

if ! /bin/rpm -q $CHEF_CLIENT_PKG > /dev/null ;then

  # Drop any old Chef packages laying around, first
  /usr/bin/yum -y erase chef || /bin/rpm -e chef
  /bin/rm -rf /opt/chef ~/.berkshelf ~/.chef /etc/chef
  /usr/bin/curl https://omnitruck.chef.io/install.sh > /root/chef-install.sh
  /bin/sh /root/chef-install.sh -v $CHEF_CLIENT_VERSION
fi

mkdir -p /etc/chef
grep ^chef_license /etc/chef/client.rb || echo "chef_license 'accept'" >> /etc/chef/client.rb
export CHEF_LICENSE="accept"


if [ -d /opt/mu/lib/cookbooks/mu-master/recipes ];then
  /opt/chef/bin/chef-apply /opt/mu/lib/cookbooks/mu-master/recipes/init.rb
else
  set +x
  echo ""
  echo "*** Installing Mu from the ${BOLD}$MU_BRANCH${NORM} branch ***"
  echo "*** Hit ^C now if that's not what you intended ***"
  echo "*** Prepend ${BOLD}MU_BRANCH=some_branch_name${NORM} to use another branch ***"
  echo ""
  sleep 10
  set -x
  /usr/bin/curl https://raw.githubusercontent.com/cloudamatic/mu/$MU_BRANCH/cookbooks/mu-master/recipes/init.rb > /root/mu-master-init-recipe.rb
  /opt/chef/bin/chef-apply /root/mu-master-init-recipe.rb
fi

echo "Launching ${BOLD}mu-configure${NORM}"
/opt/mu/bin/mu-configure $@