#!/bin/sh



MAX_RETRIES=3
SLEEP_SECONDS=5
attempt=1

while [ $attempt -le $MAX_RETRIES ]; do
    echo "Checking NTP sync (attempt $attempt/$MAX_RETRIES)..."
    if ntpq -p 2>/dev/null | grep -q '^\*'; then
        break
    fi

    echo "Not synchronized yet."

    # Only sleep if we still have retries left
    if [ $attempt -lt $MAX_RETRIES ]; then
        echo "Retrying in $SLEEP_SECONDS seconds..."
        sleep $SLEEP_SECONDS
    fi

    attempt=$((attempt + 1))
done






DIR="/mnt/data/certs"

if ! [ -d ${DIR} ]; then
    mkdir -p /mnt/data/certs
fi

CERT_NAME=barix.pem

CERT_PATH="${DIR}/${CERT_NAME}"

if ! /usr/bin/openssl x509 -in ${CERT_PATH} -noout >/dev/null 2>&1 || ! /usr/bin/openssl rsa -in ${CERT_PATH} -check -noout >/dev/null 2>&1; then
    echo "Generating new certificate..."
    


    # Generate the certificate
    /usr/bin/openssl req -newkey rsa:2048 -x509 -days 365 -nodes \
    -keyout ${CERT_PATH} -out ${CERT_PATH} \
    -subj "/emailAddress=info@barix.com/C=CH/ST=Zurich/L=Dubendorf/O=Barix AG/CN=barix.local"
    
    chmod 400 ${CERT_PATH}
    echo "Done!"
fi

