#!/bin/bash
set -u
source /usr/lib/distro-xml-fw-checker.sh
source /etc/lwr/static-config/vmm-updater/config.env

# Variables in config.env
# count: number of ic-s
# spidev: spi device name
# rst: array of reset gpio names
# rst_value: 0 or 1 (active-low or active-high)
# flash_select: array of flash select gpio names
# flash_select_value: 0 or 1 (active-low or active-high, active state connects cpu to spi chip)
# br2: BR2 package name in distro.xml
# binary: binary file without hdcp support
# hdcp_binary: binary with hdcp support
# bootstrap: array of bootstrap gpio names (optional)
# bootstrap_value: 0 or 1 (active-low or active-high, optional)
# preferred_chip: flashrom-compatible name of flash chip used by vmx ic (optional)

# Variant handling
firmware_dir=/usr/lib/firmware/lwr
version_xml_dir=/mnt/storage/permanent/fwversion
dynamic_config_dir="/etc/lwr/dynamic-config/vmm-updater"
post_updater_script="/usr/bin/vmm_updater_set_bootstrap.sh"

detected_chip_types=()
preferred_chip="${preferred_chip:-W25Q80.V}"

detect_chip_type() {
    local flash_select=$1
    local flash_select_value=$2
    local spi=$3
    local spi_speed=$4

    detected_chip_types=()

    gpioset ${flash_select}=${flash_select_value}
    local raw=$(flashrom -p linux_spi:dev=${spi},spispeed=${spi_speed})
    local error_code=$?
    gpioset ${flash_select}=$(( 1 - ${flash_select_value} ))

    if [[ ${error_code} -ne 0 ]]; then
        return ${error_code}
    fi

    local SED_COMMAND='s/.*Found[[:space:]].*chip[[:space:]]"([^"]+)".*/\1/p'
    readarray -t detected_chip_types < <(sed -nE "${SED_COMMAND}" <<< ${raw})

    return 0
}

update_firmware() {
    local flash_select=$1
    local flash_select_value=$2
    local spi=$3
    local binary=$4
    local br2=$5
    local version_xml=$6
    local hdcp_mode=$7

    echo "Start updating VMM firmware"
    detect_chip_type "${flash_select}" "${flash_select_value}" "${spi}" 8000
    for i in "${!detected_chip_types[@]}"; do
        if [[ "${detected_chip_types[i]}" == "$preferred_chip" ]]; then
            detected_chip_types=("$preferred_chip" "${detected_chip_types[@]:0:i}" "${detected_chip_types[@]:i+1}")
            break
        fi
    done
    for chip_type in "${detected_chip_types[@]}"; do
        echo "Update using chip type: ${chip_type}"
        gpioset ${flash_select}=${flash_select_value} #select flash
        flashrom -p linux_spi:dev=${spi},spispeed=8000 -w ${binary} -c "${chip_type}" 1>/dev/null
        local error_code=$?
        gpioset ${flash_select}=$(( 1 - ${flash_select_value} )) #unselect flash
        if [[ ${error_code} -eq 0 ]]; then
            echo "Updating VMM firmware was successful"
            echo "Finished updating VMM firmware, commiting changes"
            commit_firmware_version_xml ${br2} ${version_xml}
            #insert "hdcp_mode" subnode under "package" and its value
            xml ed -L -O -s /package -t elem -n hdcp_mode -v "${hdcp_mode}" ${version_xml}
            return 0
        fi
    done
    echo "Updating VMM firmware has failed"
    return 1
}

# Wait for availabe SPI
while [ ! -e "${spidev}" ]; do
    echo "SPI ${spidev} does not exist yet"
    sleep 0.1
done

# Firmware update
mkdir -p $version_xml_dir

for ((portNum=0; portNum<(count); portNum++)); do
    #Always keep vmm in reset at boot
    gpioset ${rst[${portNum}]}=${rst_value} #reset chip

    dynamic_config_name=config_${portNum}.json
    dynamic_config="${dynamic_config_dir}/${dynamic_config_name}"
    #select binary to flash based on dynamic config
    hdcp_mode="$(jq -r '.HdcpMode' "${dynamic_config}")"
    selected_binary=""
    case ${hdcp_mode} in
        "true")
            selected_binary="${hdcp_binary}"
            ;;
        "1")
            selected_binary="${hdcp_binary}"
            ;;
        "false")
            selected_binary="${binary}"
            ;;
        "0")
            selected_binary="${binary}"
            ;;
        *)
            echo "Unknown configuration in config file! ($hdcp_mode) Default hdcp binary selected for port ($portNum)."
            selected_binary="${hdcp_binary}"
            ;;
    esac

    version_xml=${version_xml_dir}/${br2}_$((portNum + 1)).xml
    is_firmware_uptodate "${br2}" ${version_xml}
    if [[ $? -ne 0 ]]; then
        #no padding needed, fw is already exactly 1048576 bytes
        update_firmware "${flash_select[${portNum}]}" \
                        "${flash_select_value}" \
                        "${spidev}" \
                        "${firmware_dir}/${selected_binary}" \
                        "${br2}" \
                        "${version_xml}" \
                        "${hdcp_mode}"
    else
        xml_hdcp_mode="$(xml sel -t -v "/package/hdcp_mode" ${version_xml})"
        if [[ "${xml_hdcp_mode}" == "${hdcp_mode}" ]]; then
            echo "VMM firmware is up-to-date, update is not required"
        else
            #no padding needed, fw is already exactly 1048576 bytes
            update_firmware "${flash_select[${portNum}]}" \
                            "${flash_select_value}" \
                            "${spidev}" \
                            "${firmware_dir}/${selected_binary}" \
                            "${br2}" \
                            "${version_xml}" \
                            "${hdcp_mode}"
        fi
    fi

    # Set bootstrap and reset gpios
    if [[ -v bootstrap[${portNum}] ]] && [[ -v bootstrap_value ]]; then
        gpioset ${bootstrap[${portNum}]}=${bootstrap_value}
    fi
    gpioset ${rst[${portNum}]}=$(( 1 - ${rst_value} )) #unreset vmm
done

#for reading flash
#flashrom -p linux_spi:dev=/dev/spidev0.1,spispeed=8000 -r /spichipx