#!/bin/bash
#
# Copyright 2016 Red Hat, Inc.
#
# NAME
#     rht-gethosts - retrieve private hosts entries to /etc/hosts
#
# SYNOPSIS
#     rht-gethosts [--reverse]
#
# DESCRIPTION
#     This tool will retrieve rht-vm-hosts appending to /etc/hosts or
#     removing those entries (with --reverse).
#
# CHANGELOG
#   * Wed May 11 2016 Robert Locke <rlocke@redhat.com>
#   - add support for RHT_ENROLLMENT -ge 512
#   * Wed Feb 10 2016 Robert Locke <rlocke@redhat.com>
#   - fix downloading rht-vmhosts on g0
#   * Sun Nov 22 2015 Robert Locke <rlocke@redhat.com>
#   - quietly skip rht-vm-hosts on f0 if does not exist
#   * Tue Oct 20 2015 Robert Locke <rlocke@redhat.com>
#   - change content.example.com to f0.ilt.example.com
#   * Fri Oct  2 2015 Robert Locke <rlocke@redhat.com>
#   - fix for running from Kickstart on foundation0
#   * Fri Sep 25 2015 Robert Locke <rlocke@redhat.com>
#   - original code

PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin

# Source some variables that we need - should provide:
# RHT_ENROLLMENT=X
# RHT_COURSE=rh124
# RHT_VMTREE=rhel7.0/x86_64
source /etc/rht
# Validate
if [[ -z "${RHT_ENROLLMENT}" || -z "${RHT_COURSE}" || -z "${RHT_VMTREE}" ]]; then
  echo "Error: missing a needed variable from /etc/rht"
  echo "RHT_ENROLLMENT = '${RHT_ENROLLMENT}'"
  echo "RHT_COURSE = '${RHT_COURSE}'"
  echo "RHT_VMTREE = '${RHT_VMTREE}'"
  exit 2
fi

# Additional functions for this shell script
function print_usage {
  local retcode=$1
  cat << EOF

This utility retrieves private VM hosts for /etc/hosts.

Usage: rht-gethosts
       rht-gethosts -r|--reverse
       rht-gethosts -h|--help

EOF
  exit ${retccode}
}

# Main area
# If I need root privileges to run, then use sudo to call myself
if [[ "${EUID}" -gt "0" ]] ; then
  echo 'Using sudo to become root.'
  sudo $0 "$@"
  exit
fi
# Parse/confirm argument passed
ARGS=$(getopt -o hr -l "help,reverse" -n "rht-gethosts" -- "$@")
if [[ $? -ne 0 ]]; then
  print_usage 1
fi
eval set -- "${ARGS}"
while true ; do
  case $1 in
    -h|--help)
      print_usage 0 ;;
    -r|--reverse)
      REVERSE=yes ; shift ;;
    --)
      shift ; break ;;
    *)
      echo "Error: bad option, $1" ; print_usage 1 ;;
  esac
done

# Always remove (perhaps the "old")
sed -i -e '/rht-vm-hosts/,$d' /etc/hosts
# Add new private hosts
if [[ -z "${REVERSE}" ]]; then
  # Do it
  [[ -f /tmp/rht-vm-hosts ]] && rm /tmp/rht-vm-hosts
  hostfile=courses/${RHT_COURSE}/${RHT_VMTREE%/*}/infrastructure/rht-vm-hosts 
  [[ ${RHT_ENROLLMENT} -eq 0 ]] && ZERO=0
  [[ $((RHT_ENROLLMENT/512)) -eq 1 ]] && ZERO=$((RHT_ENROLLMENT%512))
  if [[ -n "${ZERO}" && "${RHT_ROLE}" == "foundation" ]]; then
    hosturl=/content/${hostfile} 
    [[ -f ${hosturl} ]] && cp ${hosturl} /tmp/rht-vm-hosts
  else
    hosturl=http://foundation0.ilt.example.com/${hostfile}
    curl -f -o /tmp/rht-vm-hosts ${hosturl} &> /dev/null
  fi
  [[ -f /tmp/rht-vm-hosts ]] && cat /tmp/rht-vm-hosts >> /etc/hosts
fi

