#!/bin/sh

set -eu

readonly RED="\033[0;31m"
readonly GREEN="\033[0;32m"
readonly YELLOW="\033[0;33m"
readonly NC="\033[0m"

print_message() {
    local color=$1
    local message=$2
    echo "${color}${message}${NC}"
}

network_interface=${1:-}

print_message $GREEN "Starting Puavo Exam Room Server in Naksu2 mode..."

print_message $YELLOW "[$(date '+%Y-%m-%d %H:%M:%S')]"

workdir="${HOME}/.puavo/puavo-ers/naksu2"

print_message $GREEN "Preparing to run naksu2..."
logger -p user.notice -t puavo-ers-naksu2 \
       "preparing to run naksu2 in '${workdir}'"

if ! mkdir -p "$workdir"; then
  logger -p user.err -t puavo-ers-naksu2 "could not create '${workdir}'"
  exit 1
fi

if ! which naksu2 >/dev/null; then
  logger -p user.err -t puavo-ers-naksu2 'naksu2 not found'
  exit 1
fi

if ! docker compose version >/dev/null; then
  logger -p user.err -t puavo-ers-naksu2 'docker compose is missing'
  exit 1
fi

print_message $GREEN "Everything looks ok."

cd "$workdir"

# Start Docker only right before Naksu2, because starting it too early
# may cause issues with home directory hadling.
# (Some Abitti2 containers update the certificate file inside puavo-ers
# home directory, and if that is missing, it will end up having wrong
# ownership).

sudo -n /usr/bin/systemctl start docker.service

while true; do
  print_message $GREEN "Starting Naksu2..."
  print_message $YELLOW "[$(date '+%Y-%m-%d %H:%M:%S')]"
  logger -p user.notice -t puavo-ers-naksu2 'starting up naksu2'
  if ! naksu2; then
    print_message $RED "Naksu2 failed to start. Will try again in 5 seconds..."
    logger -p user.err -t puavo-ers-naksu2 'naksu2 failed'
  fi
  sleep 5
done
