#!/bin/sh
set -eu

case "$(uname -s)" in
    Darwin) state=/var/db/nilo-appliance ;;
    *) state=/var/lib/nilo-appliance ;;
esac
state=${1:-$state}

case "${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}" in
    de*)
        claimed='Diese Nilo Appliance ist bereits zugeordnet.'
        pending='Nilo Cloud hat die Registrierung noch nicht bestätigt. Führen Sie diesen Befehl erneut aus, sobald die Appliance online ist.'
        reference_label='Installationsreferenz'
        code_label='Zuordnungscode'
        claim_at='Als Organisationsadministrator zuordnen unter'
        ;;
    es*)
        claimed='Esta Nilo Appliance ya está vinculada.'
        pending='Nilo Cloud aún no ha confirmado el registro. Vuelve a ejecutar este comando cuando la Appliance esté en línea.'
        reference_label='Referencia de instalación'
        code_label='Código de vinculación'
        claim_at='Vincular como administrador de la organización en'
        ;;
    *)
        claimed='This Nilo Appliance is already claimed.'
        pending='Nilo Cloud has yet to confirm registration. Run this command again once the Appliance is online.'
        reference_label='Installation reference'
        code_label='Claim code'
        claim_at='Claim as an organization administrator at'
        ;;
esac

# This command runs after the package manager returns. Keep the code out of installer logs.
remaining=20
while :; do
    if [ -s "$state/service-policy.json" ]; then
        printf '%s\n' "$claimed"
        exit 0
    fi
    if [ -s "$state/claim-code" ] && [ -n "$(find "$state/claim-code" -mmin -5 -print 2>/dev/null)" ] \
        && code=$(cat "$state/claim-code" 2>/dev/null); then
        case "$code" in
            *[!0123456789abcdef]*) ;;
            *) if [ "${#code}" -eq 48 ]; then break; fi ;;
        esac
    fi
    if [ "$remaining" -eq 0 ]; then
        printf '%s\n' "$pending"
        exit 0
    fi
    remaining=$((remaining - 1))
    sleep 1
done

if [ -s "$state/installation-reference" ]; then
    printf '%s: %s\n' "$reference_label" "$(cat "$state/installation-reference")"
fi
printf '%s: %s\n%s %s\n' "$code_label" "$code" "$claim_at" 'https://app.nilo-assistant.com/appliance/link'
