#!/bin/bash
#
#  mBox OpenVPN Client Configuration State Checker v1.1.0
#  Created by Enrico Buttignol (ebuttignol@messana.tech)
#  Copyright by Messana Hydronic Technologies
#
#  Changelog:
#    Jun 15, 2026 - Massimiliano Bortolus (mbortolus@messana.tech) - Make the
#      virgin-placeholder match format-agnostic: accept regional/endpoint VPN
#      filename suffixes (e.g. -dev / -uk / -ca) by stripping a trailing
#      ALPHABETIC suffix before comparing, mirroring mht-hw-details-update.sh.
#      Previously the exact-name match (9999-9999.conf / 9999-999.conf) failed on
#      9999-9999-dev.conf, so a virgin dev/regional mBox was reported as already
#      initialized -> wizard treated it as preconfigured/corrupted.
#
#  This tool:
#    - Verifies whether the OpenVPN client configuration indicates
#      a NEW (virgin) mBox or an ALREADY INITIALIZED mBox
#    - Checks for placeholder OpenVPN client config files in /etc/openvpn/
#      (9999-9999 / 9999-999, with an optional alphabetic regional suffix)
#    - Returns "true" if the mBox is NEW / VIRGIN
#    - Returns "false" if the mBox is ALREADY INITIALIZED
#
#  Usage:
#    ./check-mbox-openvpn-client-conf
#

set -e

OPENVPN_DIR="/etc/openvpn"

is_new="false"
for file in "${OPENVPN_DIR}"/*.conf; do

    # Guard against the literal glob when no .conf file exists.
    [ -e "$file" ] || continue

    base="$(basename "$file" .conf)"

    # Strip a trailing ALPHABETIC regional/endpoint suffix (-dev / -uk / -ca): it
    # lives ONLY in the miniPC .conf filename, not in the OpenVPN common name.
    # Mirrors mht-hw-details-update.sh so the placeholder check is format-agnostic.
    # A trailing NUMERIC suffix (e.g. -01 / -05) is KEPT: it is a real sub-system
    # identity present in the CN too, so it must NOT collapse onto the placeholder.
    if [[ "$base" =~ -[A-Za-z]+$ ]]; then
        base="${base%-*}"
    fi

    if [[ "$base" == "9999-9999" || "$base" == "9999-999" ]]; then
        is_new="true"
        break
    fi
done

echo "$is_new"

exit 0
