#!/bin/bash

# Look for newly-uploaded nCipher Support Software and install it

set -e
src="/opt/ncss"
tmp="$src/zeus-tmp"

# Sanity checks etc
if [ "$1" = "--help" ]; then
   echo "Usage: $0"
   echo "Installs nCipher Support Software from tarballs in /opt/ncss"
   exit 0
fi
if [ ! -f /etc/zxtm-version ]; then
   echo "nCSS installer should only be run on appliances" >&2
   exit 1
fi
if [ `id -u` -ne 0 ]; then
   echo "nCSS installer must be run as root" >&2
   exit 1
fi
if [ ! -d $src ]; then
   echo "nCSS upgrade directory missing" >&2
   exit 1
fi
cd "$src"
rm -rf "$tmp"
archives=`ls *.tar{,.gz,.bz2} *.tgz *.tbz 2>/dev/null || true`

# Extract /opt/nfast from all tarballs
tried=0
for archive in $archives; do
   if [ $tried -lt 1 ]; then
      # There's at least one tarball; we'll do some work; introduce ourselves
      echo "Unpacking nCipher Support Software..."
      mkdir "$tmp"
      tried=1
   fi
   case "$archive" in
   *.tar.bz2|*.tbz) Z="-j" ;;
   *.tar.gz|*.tgz)  Z="-z" ;;
   *.tar)           Z=""   ;;
   esac
   tar -C "$tmp" $Z -xf "$archive" opt/nfast/
done
if [ $tried -lt 1 ]; then exit 0; fi
# Work around assumption in nCipher install script
mkdir "$tmp/opt/nfast/log"

# Start with everything owned by root; install script will fix if needed
chown -R root:root "$tmp/opt/nfast"

# Check it gave us the right files
if [ ! -x "$tmp/opt/nfast/sbin/install" ] \
   || [ ! -x "$tmp/opt/nfast/bin/rfs-sync" ] \
   || [ ! -f "$tmp/opt/nfast/toolkits/pkcs11/libcknfast.so" ]; then
   echo "nCSS tarballs did not produce required files" >&2
   rm -rf "$tmp"
   exit 1
fi

# Check for e.g. platform/library mismatch
if ! "$tmp/opt/nfast/bin/anonkneti" --version 2>&1 >/dev/null; then
   echo "nCSS tarballs did not produce working binaries" >&2
   rm -rf "$tmp"
   exit 1
fi
echo "Unpacked successfully, installing now..."

# Valid new installation; replace the old one
if [ -d /opt/nfast ]; then
   # Nobody should be using ssld; we should only be called before ZXTM startup
   killall -0 hardserver && /etc/init.d/nfast stop
   rm -rf /opt/nfast
else
   # Stolen from /opt/nfast/sbin/install: if we do this, it won't have to
   # prompt for how to create the user (and it has no other prompts)
   adduser --gecos nFast --group --shell /bin/bash --system --home /opt/nfast nfast
fi
mv "$tmp/opt/nfast" /opt/
rm -rf "$tmp"
# Will spew a lot on stdout, but that might include some of its errors
/opt/nfast/sbin/install

# All done; kill tarballs so we don't repeat
rm -f $archives
