#!/bin/bash
# Copyright 2019 Carbon Black Inc.  All rights reserved.
#
# Install blades included in the agent installation kit
#


echo_log() {
  echo "$@" 1>&2
}

install_blade() {
    local bladekit="$1"
    local tmpdir="$(mktemp -d -p /var/opt/carbonblack/tmp)"

    echo_log "Unpacking blade kit: ${bladekit##*/}"
    tar -C "$tmpdir" --no-same-owner -zxf "$bladekit"
    "${tmpdir}/bladeInstall.sh"

    rm -rf "$tmpdir"
}

# -e: Fail script if a command exits with non-zero
# -u: Fail script if undeclared variable is used
# -o pipefail: Piped command returns last non-zero exit

set -euo pipefail

# umask set here will propagate into individual blade installers
umask 077

if [ "$EUID" -ne 0 ]; then
  echo_log "Failed: Must be root to run this script."
  return 1
fi

SRC_DIR=$(dirname "$0")

mkdir -p "/var/opt/carbonblack/tmp"

for bladekit in "$SRC_DIR"/*.tar.gz; do
    # reject the case where there are no matches by double checking for existence before installation
    [ -e "$bladekit" ] || continue
    install_blade "$bladekit"
done
