#!/bin/bash
################################################################################
# cbu-installer -- Install Cloud Backup Updater for ServerMill.                #
#   Version: 1.0.000098                                                        #
#   Run this with: curl -s ${agentrepo}/servermill/cbu-installer | sh          #
################################################################################

################################################################################
# Try to recover if bzip2 is missing.                                          # 
################################################################################
export PATH=${PATH}:/bin:/usr/bin
which bzip2 >/dev/null 2>&1
if [ $? -ne 0 ]; then
  which apt-get >/dev/null 2>&1
  if [ $? -eq 0 ]; then
    apt-get -y install bzip2
  else
    which yum >/dev/null 2>&1
    if [ $? -eq 0 ]; then
      yum -y install bzip2
    fi
  fi
fi

################################################################################
# Check for required tools and environment variables.                          # 
################################################################################
export searchtools="curl bzip2 tar ls echo grep sed chmod cp rm date sleep"
export missingtools=''
export initfailure=no
for i in ${searchtools}; do which $i >/dev/null 2>&1; if [ $? -ne 0 ]; then missingtools="${missingtools} $i"; fi; done
if [ ! -z "${missingtools}" ]; then
  echo "FATAL: missing required apps: ${missingtools}" >&2
  initfailure=yes
fi
if [ -z "${agentrepo}" ]; then
  echo "FATAL: missing agentrepo URL" >&2
  initfailure=yes
fi
if [ -z "${USERNAME}" ]; then
  echo "FATAL: missing user name" >&2
  initfailure=yes
fi
if [ -z "${DATACENTER}" ]; then
  echo "FATAL: missing data center code" >&2
  initfailure=yes
fi
if [ -z "${API_KEY}" ]; then
  echo "FATAL: missing API key" >&2
  initfailure=yes
fi
if [ "${initfailure}" = "yes" ]; then
  echo "EXITING WITH FAILURE" >&2
  exit 1
fi

################################################################################
# Begin initialization.                                                        # 
################################################################################
echo "CBU installer initialization"
export initscriptname=cbu-updater-init
export initscript=/root/${initscriptname}
curl -s -k ${agentrepo}/servermill/${initscriptname} 2>/dev/null |
  sed "s|REPLACE_AGENTREPO|${agentrepo}|g" |
  sed "s|REPLACE_USERNAME|${USERNAME}|g" |
  sed "s|REPLACE_DATACENTER|${DATACENTER}|g" |
  sed "s|REPLACE_APIKEY|${API_KEY}|g" > ${initscript}
chmod 700 ${initscript}
echo "*/2 * * * * root ${initscript} > /var/log/cbu-init.log 2>&1" >> /etc/crontab

