#!/bin/bash

set -e

case "$1" in
    configure)
        if [[ $(find /sys/devices -name "tpm0") ]]; then
            echo "TPM detected"
            if [ -f "/usr/lib/systemd/system/tcsd.service" ]; then
                echo "Starting tcsd service"
                systemctl start tcsd
                ret=$?
                if [[ $ret -ne 0 ]]; then
                    echo "WARNING: FAILED TO START tcsd SERVICE, PROVISIONING WILL FAIL WITHOUT THIS SERVICE"
                fi
            echo "Adding tcsd (Trousers) to run levels 1,3,5, and 6"
            chkconfig --level 1356 tcsd on
            else
                echo "Starting tcsd service"
                service tcsd start
                ret=$?
                if [[ $ret -ne 0 ]]; then
                    echo "WARNING: FAILED TO START tcsd SERVICE, PROVISIONING WILL FAIL WITHOUT THIS SERVICE"
                fi
                echo "Adding tcsd (Trousers) to run levels 1,3,5, and 6"
                chkconfig --level 1356 tcsd on
            fi
            if [ ! -d "/sys/kernel/security/tpm0" ]; then
                echo "Mounting security fs partition"
                sed -i '$a securityfs /sys/kernel/security securityfs rw,nosuid,nodev,noexec,relatime 0 0' /etc/fstab
                mount -a
                if [ -d "/sys/kernel/security/tpm0" ]; then
	            echo "SUCCESS: security fs partition mounted"
                fi
            fi
        else
            echo "WARNING: UNABLE TO LOCATE TPM DEVICE, TPM PROVISIONING WILL FAIL"
        fi

        # install logging.properties if it doesn't already exist
        if ! [[ -f /etc/hirs/logging.properties ]]; then
            mv /etc/hirs/provisioner/logging.properties /etc/hirs/
        else
            rm /etc/hirs/provisioner/logging.properties
        fi

        hirs-provisioner -c
        ;;
    *)
        ;;
esac

exit 0