#!/bin/bash
set -ex
hostname=`ssh root@$1 hostname`
shortname=`echo $hostname | cut -d'.' -f1`
hostip=$2
sleep 2

certtool --generate-privkey > x509-ca-key.pem
echo "cn = $hostname" > ca.tmpl
echo 'ca' >> ca.tmpl
echo 'cert_signing_key' >> ca.tmpl
certtool --generate-self-signed --load-privkey x509-ca-key.pem --template ca.tmpl --outfile x509-ca.pem
echo "finish step1"
sleep 2

certtool --generate-privkey > x509-server-key.pem
echo 'organization = GnuTLS test server' > server.tmpl
echo "cn = $hostname" >> server.tmpl
echo 'tls_www_server' >> server.tmpl
echo 'encryption_key' >> server.tmpl
echo 'signing_key' >> server.tmpl
echo "dns_name = $shortname" >> server.tmpl
echo "ip_address = $hostip" >> server.tmpl
certtool --generate-certificate --load-privkey x509-server-key.pem --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem --template server.tmpl --outfile x509-server.pem
echo "finish step2"
sleep 2

certtool --generate-privkey > x509-client-key.pem
echo "cn = $hostname" > client.tmpl
echo 'tls_www_client' >> client.tmpl
echo 'encryption_key' >> client.tmpl
echo 'signing_key' >> client.tmpl
echo "ip_address = $hostip" >> client.tmpl
echo "dns_name = $shortname" >> client.tmpl
certtool --generate-certificate --load-privkey x509-client-key.pem --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem --template client.tmpl --outfile x509-client.pem
echo "finish step3"
sleep 2

tls_dir=`pwd`
cp x509-ca.pem ca-cert.pem
cp x509-ca-key.pem ca-key.pem
cp x509-client.pem client-cert.pem
cp x509-client-key.pem client-key.pem
scp x509-ca.pem root@$1:$tls_dir/ca-cert.pem
scp x509-ca-key.pem root@$1:$tls_dir/ca-key.pem
scp x509-server.pem root@$1:$tls_dir/server-cert.pem
scp x509-server-key.pem root@$1:$tls_dir/server-key.pem
rm -rf x509*
rm -rf *tmpl

echo "finish step4, that's all"