#!/bin/bash
# -*- mode: shell-script; coding: utf-8 -*-
#
# Copyright 2002-2019 Cendio AB.
# For more information, see http://www.cendio.com

[ -h "$0" ] && ORIGIN=`ls -l "$0" | sed "s/.*-> //g"` || ORIGIN="$0"
ORIGIN=`(cd "\`dirname \"$ORIGIN\"\`"; pwd -P 2>/dev/null || pwd)`

umask 077

if [ $# -eq 0 ] ; then
        echo $"Usage: `basename $0` <hostname>"
	echo "Common usage:"
	echo "$0 \`hostname\`"
        exit 1
fi

if openssl req -new -x509 -config <(
cat << EOF

[ req ]
prompt                  = no
default_bits            = 2048
encrypt_key             = no
default_md              = sha256
default_keyfile         = ${ORIGIN}/server.key
distinguished_name      = req_dn
x509_extensions         = v3_exts
string_mask             = utf8only

[ req_dn ]
organizationName = ThinLinc Customer
organizationalUnitName = ThinLinc Web Access
commonName = $1

[ v3_exts ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical,CA:true
subjectAltName = DNS:$1
keyUsage = keyCertSign,digitalSignature,keyEncipherment
extendedKeyUsage = serverAuth
nsCertType = server,sslCA

EOF
        ) -out ${ORIGIN}/server.crt -days 365 ; then
    echo "Done."
    echo ""
    echo "Consider updating agent_hostname, using:"
    echo "sudo /opt/thinlinc/bin/tl-config /vsmagent/agent_hostname=$1"
    echo "sudo systemctl restart vsmagent.service"
elif [ $? -eq 127 ] ; then
    echo "Error: OpenSSL, which is a required tool for this command, was not found."
else
    echo "Error: OpenSSL exited with error code $?"
fi
