#!/bin/sh
get_tpm_apikey() {
    lasthdl=""
    if [ -c /dev/tpmrm0 ]; then
        for hdl in $(tpm2_getcap handles-persistent|awk '{print $2}'); do
            tpm2_startauthsession --policy-session --session=session.ctx
            tpm2_policypcr -Q --session=session.ctx --pcr-list="sha256:15" --policy=pcr15.sha256.policy
            unsealeddata=$(tpm2_unseal --auth=session:session.ctx -Q -c $hdl 2>/dev/null)
            tpm2_flushcontext session.ctx
            if echo $unsealeddata | grep "^CONFLUENT_APIKEY:" > /dev/null; then
                confluent_apikey=${unsealeddata#CONFLUENT_APIKEY:}
                echo $confluent_apikey > /etc/confluent/confluent.apikey
                if [ -n "$lasthdl" ]; then
                    tpm2_evictcontrol -c $lasthdl
                fi
                lasthdl=$hdl
            fi
        done
    fi
    if [ ! -z "$confluent_apikey" ]; then
        if ! curl --cacert /etc/confluent/ca.pem  -sSf -H "CONFLUENT_NODENAME: $confluent_nodename"  -H "CONFLUENT_APIKEY: $confluent_apikey" https://${confluent_http_mgr}/confluent-api/self/myattribs > /dev/null; then
            tpm2_evictcontrol -c $lasthdl
            confluent_apikey=""
        fi
    fi
}

get_remote_apikey() {
    while [ -z "$confluent_apikey" ]; do
        /opt/confluent/bin/clortho $confluent_nodename $confluent_mgr > /etc/confluent/confluent.apikey
        if grep ^SEALED: /etc/confluent/confluent.apikey > /dev/null; then
            # we don't support remote sealed api keys anymore
            echo > /etc/confluent/confluent.apikey
        fi
        confluent_apikey=$(cat /etc/confluent/confluent.apikey)
        if [ -z "$confluent_apikey" ]; then
            echo "Unable to acquire node api key, set deployment.apiarmed=once on node '$confluent_nodename', retrying..."
            sleep 10
        elif [ -c /dev/tpmrm0 ]; then
            tmpdir=$(mktemp -d)
            cd $tmpdir
            tpm2_startauthsession --session=session.ctx
            tpm2_policypcr -Q --session=session.ctx --pcr-list="sha256:15" --policy=pcr15.sha256.policy
            tpm2_createprimary -G ecc -Q --key-context=prim.ctx
            (echo -n "CONFLUENT_APIKEY:";cat /etc/confluent/confluent.apikey) | tpm2_create -Q --policy=pcr15.sha256.policy --public=data.pub --private=data.priv -i - -C prim.ctx
            tpm2_load -Q --parent-context=prim.ctx --public=data.pub --private=data.priv --name=confluent.apikey --key-context=data.ctx
            tpm2_evictcontrol -Q -c data.ctx
            tpm2_flushcontext session.ctx
            cd - > /dev/null
            rm -rf $tmpdir
        fi
    done
}

if ! grep console= /proc/cmdline > /dev/null; then
    autocons=$(/opt/confluent/bin/autocons)
    autocons=${autocons##*/}
    echo "Automatic console configured for $autocons"
fi
echo sshd:x:30:30:SSH User:/var/empty/sshd:/sbin/nologin >> /etc/passwd
modprobe ib_ipoib
modprobe ib_umad
modprobe hfi1
modprobe mlx5_ib
cd /sys/class/net
for nic in *; do
    ip link set $nic up
done
mkdir -p /etc/confluent
cd - > /dev/null
mkdir -p /etc/ssl/certs
cat /tls/*.pem > /etc/ssl/certs/ca-certificates.crt
cat /tls/*.pem > /etc/confluent/ca.pem
/opt/confluent/bin/copernicus -t > /etc/confluent/confluent.info
TRIES=0
while ! grep ^EXTMGRINFO: /etc/confluent/confluent.info | awk -F'|' '{print $3}' | grep 1 > /dev/null && [ "$TRIES" -lt 30 ]; do
    TRIES=$((TRIES + 1))
    /opt/confluent/bin/copernicus -t > /etc/confluent/confluent.info
    sleep 1
done
confluent_mgr=$(grep '^EXTMGRINFO:.*1$' /etc/confluent/confluent.info | head -n 1 | awk -F': ' '{print $2}' | awk -F'|' '{print $1}')
if [ -z "$confluent_mgr" ]; then
    confluent_mgr=$(grep ^MANAGER: /etc/confluent/confluent.info|head -n 1 | awk '{print $2}')
fi
if echo $confluent_mgr | grep : >/dev/null; then
    confluent_http_mgr="[$confluent_mgr]"
else
    confluent_http_mgr=$confluent_mgr
fi
confluent_nodename=$(grep ^NODENAME: /etc/confluent/confluent.info |awk '{print $NF}')
hostname $confluent_nodename
get_tpm_apikey
if [ -z "$confluent_apikey" ]; then
    get_remote_apikey
fi
if echo $confluent_mgr | grep '%' > /dev/null; then
    echo $confluent_mgr | awk -F% '{print $2}' > /tmp/confluent.ifidx
    ifidx=$(cat /tmp/confluent.ifidx)
    ifname=$(ip link |grep ^$ifidx:|awk '{print $2}')
    ifname=${ifname%:}
fi
curl --cacert /etc/confluent/ca.pem  -sSf -H "CONFLUENT_NODENAME: $confluent_nodename"  -H "CONFLUENT_APIKEY: $confluent_apikey" https://${confluent_http_mgr}/confluent-api/self/deploycfg2 > /etc/confluent/confluent.deploycfg
if [ ! -z "$autocons" ] && grep textconsole: true /etc/confluent/confluent.deploycfg > /dev/null; then /opt/confluent/bin/autocons -c > /dev/null; fi
v6meth=$(grep ^ipv6_method: /etc/confluent/confluent.deploycfg|awk '{print $2}')
if [ "$v6meth" = static ]; then
    v6addr=$(grep ^ipv6_address: /etc/confluent/confluent.deploycfg | awk '{print $2}')
    v6prefix=$(grep ^ipv6_prefix: /etc/confluent/confluent.deploycfg | awk '{print $2}')
    ip addr add dev $ifname $v6addr/$v6prefix
    v6gw=$(grep ^ipv6_gateway: /etc/confluent/confluent.deploycfg | awk '{print $2}')
    if [ ! -z "$v6gw" -a "$v6gw" != "null" ]; then
        ip route add default via $v6gw
    fi
fi
v4meth=$(grep ^ipv4_method: /etc/confluent/confluent.deploycfg|awk '{print $2}')
if [ "$v4meth" = static ]; then
    v4addr=$(grep ^ipv4_address: /etc/confluent/confluent.deploycfg | awk '{print $2}')
    v4prefix=$(grep ^prefix: /etc/confluent/confluent.deploycfg | awk '{print $2}')
    ip addr add dev $ifname $v4addr/$v4prefix
    v4gw=$(grep ^ipv4_gateway: /etc/confluent/confluent.deploycfg | awk '{print $2}')
    if [ ! -z "$v4gw" -a "$v4gw" != "null" ]; then
        ip route add default via $v4gw
    fi
fi
mkdir -p /run/sshd
mkdir -p /etc/ssh
echo Port 2222 > /etc/ssh/sshd_config
ssh-keygen -A
for k in /etc/ssh/*key.pub; do
    certfile=$(echo $k|sed -e s/.pub/-cert.pub/)
    privkey=$(echo $k|sed -e s/.pub//)
    curl --cacert /etc/confluent/ca.pem -sSf -H "CONFLUENT_NODENAME: $confluent_nodename"  -H "CONFLUENT_APIKEY: $confluent_apikey"  -d @$k https://${confluent_http_mgr}/confluent-api/self/sshcert >> $certfile
    if [ -s $certfile ]; then
        if ! grep $certfile /etc/ssh/sshd_config > /dev/null; then
            echo HostCertificate $certfile >> /etc/ssh/sshd_config
        fi
        if ! grep "HostKey $privkey" /etc/ssh/sshd_config > /dev/null; then
            echo HostKey $privkey >> /etc/ssh/sshd_config
        fi
    fi
done
/usr/sbin/sshd
mkdir -p /root/.ssh
cat /ssh/*pubkey > /root/.ssh/authorized_keys
if [ -c /dev/tpmrm0 ]; then
    tpm2_pcrextend 15:sha256=2fbe96c50dde38ce9cd2764ddb79c216cfbcd3499568b1125450e60c45dd19f2
fi
confluent_profile=$(grep ^profile: /etc/confluent/confluent.deploycfg| awk '{print $2}')
confluent_proto=$(grep ^protocol: /etc/confluent/confluent.deploycfg| awk '{print $2}')
confluent_mgr=$(grep ^deploy_server: /etc/confluent/confluent.deploycfg| awk '{print $2}')
curl -sf https://$confluent_mgr/confluent-public/os/$confluent_profile/scripts/functions > /etc/confluent/functions
exec /bin/bash /etc/confluent/functions source_remote imageboot.sh
