#!/bin/sh
#
# 2017.06.25, Koji Takeuchi
#
# Set variables
auth='-u USERNAME -p PASSWORD'
domain=fms.example.com
#
keyPath=/etc/dehydrated/certs
tmpPath=/tmp/certs
#
# Prepare a temporary directory.
# Copy the certs here, then import copied certs.
# Because the ogirinal certs downloaded by Certbot/dehydrated are 
# synbolic links, and...
# FileMaker Server doesn't handle certificates properly when they are symbolic links
if [ ! -d "$tmpPath" ]; then
	mkdir "$tmpPath"
	chmod 700 "$tmpPath"
fi
#
cp ${keyPath}/${domain}/privkey.pem $tmpPath/
cp ${keyPath}/${domain}/cert.pem $tmpPath/
cp ${keyPath}/${domain}/fullchain.pem $tmpPath/
#
# Delete existing certificates and restart FileMaker Server.
fmsadmin certificate delete -y $auth
fmsadmin close -f -y $auth
service fmshelper restart
#
# Pause awhile and restart the admin server (for good luck charm)
sleep 10
fmsadmin restart adminserver -y $auth
sleep 10
#
# Import certificates and restart FileMaker Server
fmsadmin certificate import -y --keyfile "${tmpPath}/privkey.pem" --intermediateCA "${tmpPath}/fullchain.pem" "${tmpPath}/cert.pem" $auth
service fmshelper restart
rm -rf "${tmpPath}"
#
# Pause awhile and restart the admin server (for good luck charm)
sleep 10
fmsadmin restart adminserver -y $auth
sleep 15
#
# Re-open the databases (if necessary, depends on "Automatically open" settings)
files=$(fmsadmin list files $auth | grep fmp12 | grep -v grep)
if [ ! -n "$files" ]; then
	fmsadmin open $auth
fi
