#!/bin/sh
# GUID check/build script

# -------- Global Vars --------
SCRIPT_NAME="${0##*/}"
QUIET=0
MODE=""

# -------- Functions --------
lower() {
    local s
    s="$1"
    # lowercase only the letters found in a MAC address
    s="${s//A/a}"; s="${s//B/b}"; s="${s//C/c}"
    s="${s//D/d}"; s="${s//E/e}"; s="${s//F/f}"
    printf "%s" "$s"
}

# Build GUID from eth0 MAC and serialnum
compute_guid() {
    local mac_line mac_addr serial_num de hex

    if ! IFS= read -r mac_line < /sys/class/net/eth0/address; then
        return 3
    fi
    mac_line="$(lower "$mac_line")"
    mac_addr="${mac_line//:/}"

    serial_num="$(serialnum 2>/dev/null)" || serial_num=""
    [ -n "$mac_addr" ] && [ -n "$serial_num" ] || return 3

    de="00de"
    hex="${de}${mac_addr}$(lower "$serial_num")"

    # Insert hyphens into the GUID format
    printf "%s-%s-%s-%s-%s" \
        "${hex:0:8}" "${hex:8:4}" "${hex:12:4}" "${hex:16:4}" "${hex:20:12}"
}

# Show help
show_help() {
    cat <<EOF
Usage:
  $SCRIPT_NAME             Print GUID (UCI if set, else computed)
  $SCRIPT_NAME check       Compare UCI vs computed (exit 0/1/2/3)
  $SCRIPT_NAME -c|--check  Same as 'check'
  $SCRIPT_NAME -q|--quiet  Suppress output (use with check)
  $SCRIPT_NAME -h|--help   Show this help

Exit codes for check mode:
  0 - GUIDs match
  1 - GUIDs differ
  2 - UCI guid missing
  3 - Unable to compute GUID (missing MAC or serial)
EOF
}

# -------- Arg parsing --------
while [ $# -gt 0 ]; do
    case "$1" in
        check|-c|--check) MODE="check" ;;
        -q|--quiet) QUIET=1 ;;
        -h|--help) show_help; exit 0 ;;
        *) MODE="" ;;  # default mode
    esac
    shift
done

UCI_GUID="$(uci -q get system.@system[0].guid 2>/dev/null)"

if [ "$MODE" = "check" ]; then
    BUILT_GUID="$(compute_guid)"; rc=$?
    if [ $rc -ne 0 ] || [ -z "$BUILT_GUID" ]; then
        [ $QUIET -eq 0 ] && echo "ERROR: unable to compute guid (missing MAC or serial)."
        exit 3
    fi
    if [ -z "$UCI_GUID" ]; then
        [ $QUIET -eq 0 ] && echo "MISSING: UCI guid is not set."
        exit 2
    fi
    if [ "$(lower "$UCI_GUID")" = "$(lower "$BUILT_GUID")" ]; then
        [ $QUIET -eq 0 ] && echo "MATCH: UCI guid matches computed guid."
        exit 0
    else
        [ $QUIET -eq 0 ] && {
            echo "DIFFERENT: UCI guid does not match computed guid."
            echo "UCI:   $(lower "$UCI_GUID")"
            echo "Built: $(lower "$BUILT_GUID")"
        }
        exit 1
    fi
else
    GUID="$UCI_GUID"
    if [ -z "$GUID" ]; then
        GUID="$(compute_guid)" || {
            echo "ERROR: unable to compute guid (missing MAC or serial)."
            exit 3
        }
    fi
    printf "%s\n" "$(lower "$GUID")"
fi
