#!/bin/bash
# Copyright (c) 2014 Cloudera, Inc. All rights reserved.

# Install/Remove alternatives entries for parcels

# This ridiculousness is required on SLES.
function safe_deregister_bin {
  NAME="$1"
  DEST="$2"
  SOURCE="$3"
  # If the binary doesn't exist, simply deregister it, since we need to keep alternatives DB in sync
  if [ ! -e "$DEST" ]; then
    $SUDO update-alternatives --remove "$NAME" "$SOURCE"
  # If the binary is a symlink pointing to alternatives, then we will just let alternatives manage the removal
  elif [ -L "$DEST" ] && [ "$(readlink $DEST)" = "/etc/alternatives/$NAME" ]; then
    $SUDO update-alternatives --remove "$NAME" "$SOURCE"
  # Otherwise, we have to defensively remove it
  else
    # Make a copy of the binary if it's not managed by alternatives
    cp -a "$DEST" "${DEST}~"
    # Then deregister the alternative, which on SLES may remove the physical file
    $SUDO update-alternatives --remove "$NAME" "$SOURCE"
    # If the file was in fact removed during the de-registration process, restore it
    if [ ! -e "$DEST" ]; then
      mv "${DEST}~" "$DEST"
    fi
    # In all cases, forcefully remove the backup
    rm -f "${DEST}~"
  fi
}

# debug
set -x
set -e

if [[ $# -lt 6 ]]; then
 echo "Insufficient number of arguments"
 exit -1
fi

if [[ -z "$PARCELS_ROOT" ]]; then
  echo "PARCELS_ROOT must be set"
  exit -1
fi

if [[ -z "$PARCEL_DIRNAME" ]]; then
  echo "PARCEL_DIRNAME must be set"
  exit -1
fi

SUSE_RELEASES="suse|sles"

MODE="$1"
NAME="$2"
DEST="$3"
SOURCE="$PARCELS_ROOT/$PARCEL_DIRNAME/$4"
PRIORITY="$5"
IS_DIRECTORY="$6"

if [[ "$MODE" == "activate" ]]; then
  if [[ "$IS_DIRECTORY" == "True" ]]; then
    $SUDO mkdir -p `dirname "$DEST"`
  fi
  $SUDO update-alternatives --install "$DEST" "$NAME" "$SOURCE" "$PRIORITY"
elif [[ "$MODE" == "deactivate" ]]; then
  if egrep -i $SUSE_RELEASES /etc/*release; then
    safe_deregister_bin "$NAME" "$DEST" "$SOURCE"
  else
    $SUDO update-alternatives --remove "$NAME" "$SOURCE"
  fi
  if [[ "$IS_DIRECTORY" == "True" ]]; then
    # Don't return an error if this fails. It is opportunistic
    set +e
    rmdir --ignore-fail-on-non-empty `dirname "$DEST"`
    set -e
  fi
else
  echo "Unknown mode: $MODE"
  exit -1
fi
