#!/bin/bash

set -e

SETTINGS_SERVICE="xyz.openbmc_project.Settings"
GUID_OBJPATH="/xyz/openbmc_project/inventory/item/bmc"
GUID_INTERFACE="xyz.openbmc_project.Common.UUID"
BMC_INTERFACE="xyz.openbmc_project.Inventory.Item.Bmc"
SYSTEM_GUID_PROPERTY="UUID"
DEVICE_GUID_PROPERTY="DeviceGUID"

EEPROM_SERVICE="com.luxshare.eeprom"
EEPROM_OBJPATH="/com/luxshare/eeprom/baseboard"
EEPROM_INTERFACE="com.luxshare.eeprom"
EEPROM_SYSTEM_GUID_PROPERTY="SystemGUID"
EEPROM_DEVICE_GUID_PROPERTY="DeviceGUID"

echo "generate device&system guid from machine-id"
guid_str=$(systemd-id128 machine-id --app-specific=e0e17376646147daa50cd0cc64124578)

system_data_raw=$(busctl get-property ${EEPROM_SERVICE} ${EEPROM_OBJPATH} ${EEPROM_INTERFACE} ${EEPROM_SYSTEM_GUID_PROPERTY})

#remove ay 16
system_GUID=$(echo $system_data_raw | sed 's/ay [0-9]\+ //')

read -a data <<< "$system_GUID"

hex_data=()
#dec==>hex
for decimal_value in "${data[@]}"; do
    hex_value=$(printf "%02x" "$decimal_value")
    hex_data+=("$hex_value")
done

echo "Read system GUID from eeprom service : ${system_GUID}"
if [[ "$system_GUID" == "255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255" ]];then
    busctl set-property "${SETTINGS_SERVICE}" "${GUID_OBJPATH}" "${GUID_INTERFACE}" "${SYSTEM_GUID_PROPERTY}" s "${guid_str:0:8}"-"${guid_str:8:4}"-"${guid_str:12:4}"-"${guid_str:16:4}"-"${guid_str:20:12}"
else
    busctl set-property "${SETTINGS_SERVICE}" "${GUID_OBJPATH}" "${GUID_INTERFACE}" "${SYSTEM_GUID_PROPERTY}" s "${hex_data[0]}""${hex_data[1]}""${hex_data[2]}""${hex_data[3]}"-"${hex_data[4]}""${hex_data[5]}"-"${hex_data[6]}""${hex_data[7]}"-"${hex_data[8]}""${hex_data[9]}"-"${hex_data[10]}""${hex_data[11]}""${hex_data[12]}""${hex_data[13]}""${hex_data[14]}""${hex_data[15]}"
fi

device_data_raw=$(busctl get-property ${EEPROM_SERVICE} ${EEPROM_OBJPATH} ${EEPROM_INTERFACE} ${EEPROM_DEVICE_GUID_PROPERTY})

device_GUID=$(echo $device_data_raw | sed 's/ay [0-9]\+ //')

read -a data <<< "$device_GUID"

hex_data=()
#dec==>hex
for decimal_value in "${data[@]}"; do
    hex_value=$(printf "%02x" "$decimal_value")
    hex_data+=("$hex_value")
done

echo "Read device GUID from eeprom : ${device_GUID}"
if [[ "$device_GUID" == "255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255" ]];then
    busctl set-property "${SETTINGS_SERVICE}" "${GUID_OBJPATH}" "${BMC_INTERFACE}" "${DEVICE_GUID_PROPERTY}" s "${guid_str:0:8}"-"${guid_str:8:4}"-"${guid_str:12:4}"-"${guid_str:16:4}"-"${guid_str:20:12}"
else
    busctl set-property "${SETTINGS_SERVICE}" "${GUID_OBJPATH}" "${BMC_INTERFACE}" "${DEVICE_GUID_PROPERTY}" s "${hex_data[0]}""${hex_data[1]}""${hex_data[2]}""${hex_data[3]}"-"${hex_data[4]}""${hex_data[5]}"-"${hex_data[6]}""${hex_data[7]}"-"${hex_data[8]}""${hex_data[9]}"-"${hex_data[10]}""${hex_data[11]}""${hex_data[12]}""${hex_data[13]}""${hex_data[14]}""${hex_data[15]}"
fi
