#!/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"

creat_GUID_str()
{
    GUID=$1
    for((i=0;i<4;i++));
    do
    data[i]=${GUID:i*2+1:2}
    done

    for((i=4;i<6;i++));
    do
    data[i]=${GUID:i*2+2:2}
    done

    for((i=6;i<8;i++));
    do
    data[i]=${GUID:i*2+3:2}
    done

    for((i=8;i<10;i++));
    do
    data[i]=${GUID:i*2+4:2}
    done

    for((i=10;i<16;i++));
    do
    data[i]=${GUID:i*2+5:2}
    done
}

system_GUID=$(busctl get-property ${SETTINGS_SERVICE} ${GUID_OBJPATH} ${GUID_INTERFACE} ${SYSTEM_GUID_PROPERTY} | awk '{print $2}')
creat_GUID_str "${system_GUID}"
echo "Write system GUID to eeprom : ${system_GUID}"
busctl set-property ${EEPROM_SERVICE} ${EEPROM_OBJPATH} ${EEPROM_INTERFACE} ${EEPROM_SYSTEM_GUID_PROPERTY} ay 16 0x"${data[0]}" 0x"${data[1]}" 0x"${data[2]}" 0x"${data[3]}" 0x"${data[4]}" 0x"${data[5]}" 0x"${data[6]}" 0x"${data[7]}" 0x"${data[8]}" 0x"${data[9]}" 0x"${data[10]}" 0x"${data[11]}" 0x"${data[12]}" 0x"${data[13]}" 0x"${data[14]}" 0x"${data[15]}"

device_GUID=$(busctl get-property ${SETTINGS_SERVICE} ${GUID_OBJPATH} ${BMC_INTERFACE} ${DEVICE_GUID_PROPERTY} | awk '{print $2}')
creat_GUID_str  "${device_GUID}"
echo "Write device GUID to eeprom : ${device_GUID}"
busctl set-property ${EEPROM_SERVICE} ${EEPROM_OBJPATH} ${EEPROM_INTERFACE} ${EEPROM_DEVICE_GUID_PROPERTY} ay 16 0x"${data[0]}" 0x"${data[1]}" 0x"${data[2]}" 0x"${data[3]}" 0x"${data[4]}" 0x"${data[5]}" 0x"${data[6]}" 0x"${data[7]}" 0x"${data[8]}" 0x"${data[9]}" 0x"${data[10]}" 0x"${data[11]}" 0x"${data[12]}" 0x"${data[13]}" 0x"${data[14]}" 0x"${data[15]}"
