#!/bin/bash

# This file is tracked by plays/razor/templates/install_client.sh in
# ansible/environment because it is related to the razor template files. It
# needs to be copied manually to the target location as defined by the razor
# broker's install_sh setting.

# The script is a stripped down replacement for
# http://www.chef.io/chef/install.sh.

# Theory of operation:
#
# We could add a cinc.broker to replace chef.broker, but using the chef.broker
# is trivial and good enough for now.
#
# We avoid having to build some magic for guessing the correct filename,
# and we get the sha256sum from the cluster's local razor server instead of
# repo.x-ion.de (which may send its data using HTTP over the internet).
#
# The chef.broker uses process substitution to download and start this script.
# The line in brokers/chef.broker/install.erb looks like this:
#
# bash <(wget ${install_sh} -O -) -v ${version_string}
#
# The "<(...)" creates a named pipe which is then passed to bash for
# execution along with the argument version_string. Because the version_string
# argument is left unquoted, the string is split into multiple arguments if
# white space is present. We exploit the sloppy coding by separating our two
# arguments by a space in the razor configuration. The chef.broker then
# passes three arguments to this script: "-v", <url>, and <sha256>.

set -o errexit -o nounset

echo "Starting install_cinc.sh"

url=$2
echo "url: $url"
filename=$(basename "$url")

sha256=$3
echo "sha256: $sha256"

cd /root
echo "Downloading $url"
wget --no-verbose "$url"

echo "Checking sha256"
csum=$(sha256sum "$filename" | cut -f1 -d" ")
if [ "$csum" != "$sha256" ]; then
    echo "sha256 checksum for $filename: $csum"
    echo "ERROR Checksums don't match."
    exit 1
fi

echo "Installing $filename"
dpkg -i "$filename"

# Create symlink so cinc finds the configuration files placed in /etc/chef
# by the chef.broker.
echo "Creating symlink /etc/cinc"
ln -s chef /etc/cinc

# fix the cert issue
echo "fix the cert issue"
# mv the cacert.pem file to cacert.pem_old
mv /opt/cinc/embedded/ssl/certs/cacert.pem /opt/cinc/embedded/ssl/certs/cacert.pem_old
# load the newer one
wget http://repo.x-ion.de/files/chef/cacert.pem -O /opt/cinc/embedded/ssl/certs/cacert.pem
# cp the trusted cacert.pem file to the position, sensu will search for
#mkdir -p /opt/sensu/embedded/ssl/certs/
#cp /opt/cinc/embedded/ssl/certs/cacert.pem /opt/sensu/embedded/ssl/certs/cacert.pem
# info
echo "newer cert file should be active"

apt update
apt install -y gpg
