#!/usr/bin/env bash
# This script was generated by bashly 1.0.4 (https://bashly.dannyb.co)
# Modifying it manually is not recommended

# :wrapper.bash3_bouncer
if [[ "${BASH_VERSINFO:-0}" -lt 4 ]]; then
  printf "bash version 4 or higher is required\n" >&2
  exit 1
fi

# :command.master_script

# :command.version_command
version_command() {
  echo "$version"
}

# :command.usage
dcu_usage() {
  if [[ -n $long_usage ]]; then
    printf "dcu - Dasharo Configuration Utility\n"
    echo

  else
    printf "dcu - Dasharo Configuration Utility\n"
    echo

  fi

  printf "%s\n" "Usage:"
  printf "  dcu COMMAND\n"
  printf "  dcu [COMMAND] --help | -h\n"
  printf "  dcu --version | -v\n"
  echo
  # :command.usage_commands
  printf "%s\n" "Commands:"
  printf "  %s   Edit SMBIOS data in a firmware image\n" "smbios"
  printf "  %s   Insert custom logo boot splash into firmware image\n" "logo  "
  echo

  # :command.long_usage
  if [[ -n $long_usage ]]; then
    printf "%s\n" "Options:"

    # :command.usage_fixed_flags
    printf "  %s\n" "--help, -h"
    printf "    Show this help\n"
    echo
    printf "  %s\n" "--version, -v"
    printf "    Show version number\n"
    echo

    # :command.usage_examples
    printf "%s\n" "Examples:"
    printf "  dcu smbios coreboot.rom -u 96bcfa1a-42b4-6717-a44c-d8bbc18cbea4 -s D07229051\n"
    printf "  dcu logo coreboot.rom -l bootsplash.bmp\n"
    echo

  fi
}

# :command.usage
dcu_smbios_usage() {
  if [[ -n $long_usage ]]; then
    printf "dcu smbios - Edit SMBIOS data in a firmware image\n"
    echo

  else
    printf "dcu smbios - Edit SMBIOS data in a firmware image\n"
    echo

  fi

  printf "Alias: s\n"
  echo

  printf "%s\n" "Usage:"
  printf "  dcu smbios DASHARO_ROM_FILE [OPTIONS]\n"
  printf "  dcu smbios --help | -h\n"
  echo

  # :command.long_usage
  if [[ -n $long_usage ]]; then
    printf "%s\n" "Options:"

    # :command.usage_flags
    # :flag.usage
    printf "  %s\n" "--uuid, -u UUID"
    printf "    UUID in RFC4122 format to be set in SMBIOS type 1 structure\n"
    echo

    # :flag.usage
    printf "  %s\n" "--serial-number, -s SERIAL"
    printf "    Serial number to be set in SMBIOS type 1 and type 2 structure\n"
    echo

    # :command.usage_fixed_flags
    printf "  %s\n" "--help, -h"
    printf "    Show this help\n"
    echo

    # :command.usage_args
    printf "%s\n" "Arguments:"

    # :argument.usage
    printf "  %s\n" "DASHARO_ROM_FILE"
    printf "    Dasharo firmware file (e.g. coreboot.rom)\n"
    echo

    # :command.usage_examples
    printf "%s\n" "Examples:"
    printf "  dcu smbios coreboot.rom -u 96bcfa1a-42b4-6717-a44c-d8bbc18cbea4\n"
    printf "  dcu smbios coreboot.rom -s D07229051\n"
    printf "  dcu smbios coreboot.rom -u 96bcfa1a-42b4-6717-a44c-d8bbc18cbea4 -s D07229051\n"
    echo

  fi
}

# :command.usage
dcu_logo_usage() {
  if [[ -n $long_usage ]]; then
    printf "dcu logo - Insert custom logo boot splash into firmware image\n"
    echo

  else
    printf "dcu logo - Insert custom logo boot splash into firmware image\n"
    echo

  fi

  printf "Alias: l\n"
  echo

  printf "%s\n" "Usage:"
  printf "  dcu logo DASHARO_ROM_FILE [OPTIONS]\n"
  printf "  dcu logo --help | -h\n"
  echo

  # :command.long_usage
  if [[ -n $long_usage ]]; then
    printf "%s\n" "Options:"

    # :command.usage_flags
    # :flag.usage
    printf "  %s\n" "--logo, -l LOGO (required)"
    printf "    Custom logo in BMP/PNG/JPG/SVG format to be displayed on boot\n"
    echo

    # :command.usage_fixed_flags
    printf "  %s\n" "--help, -h"
    printf "    Show this help\n"
    echo

    # :command.usage_args
    printf "%s\n" "Arguments:"

    # :argument.usage
    printf "  %s\n" "DASHARO_ROM_FILE"
    printf "    Dasharo firmware file (e.g. coreboot.rom)\n"
    echo

    # :command.usage_examples
    printf "%s\n" "Examples:"
    printf "  dcu logo coreboot.rom -l bootsplash.bmp\n"
    echo

  fi
}

# :command.normalize_input
normalize_input() {
  local arg flags

  while [[ $# -gt 0 ]]; do
    arg="$1"
    if [[ $arg =~ ^(--[a-zA-Z0-9_\-]+)=(.+)$ ]]; then
      input+=("${BASH_REMATCH[1]}")
      input+=("${BASH_REMATCH[2]}")
    elif [[ $arg =~ ^(-[a-zA-Z0-9])=(.+)$ ]]; then
      input+=("${BASH_REMATCH[1]}")
      input+=("${BASH_REMATCH[2]}")
    elif [[ $arg =~ ^-([a-zA-Z0-9][a-zA-Z0-9]+)$ ]]; then
      flags="${BASH_REMATCH[1]}"
      for ((i = 0; i < ${#flags}; i++)); do
        input+=("-${flags:i:1}")
      done
    else
      input+=("$arg")
    fi

    shift
  done
}
# :command.inspect_args
inspect_args() {
  if ((${#args[@]})); then
    readarray -t sorted_keys < <(printf '%s\n' "${!args[@]}" | sort)
    echo args:
    for k in "${sorted_keys[@]}"; do echo "- \${args[$k]} = ${args[$k]}"; done
  else
    echo args: none
  fi

  if ((${#other_args[@]})); then
    echo
    echo other_args:
    echo "- \${other_args[*]} = ${other_args[*]}"
    for i in "${!other_args[@]}"; do
      echo "- \${other_args[$i]} = ${other_args[$i]}"
    done
  fi

  if ((${#deps[@]})); then
    readarray -t sorted_keys < <(printf '%s\n' "${!deps[@]}" | sort)
    echo
    echo deps:
    for k in "${sorted_keys[@]}"; do echo "- \${deps[$k]} = ${deps[$k]}"; done
  fi

}

# :command.command_functions
# :command.function
dcu_smbios_command() {
  # src/smbios_command.sh
  # SPDX-FileCopyrightText: 2023 3mdeb <contact@3mdeb.com>
  #
  # SPDX-License-Identifier: Apache-2.0

  # inspect_args

  DASHARO_ROM="${args[dasharo_rom_file]}"
  SYSTEM_UUID="${args[--uuid]}"
  SERIAL_NUMBER="${args[--serial-number]}"

  set_uuid() {
    local _uuid="$1"

    if ! echo "${CB_CONFIG}" | grep -q "CONFIG_DRIVERS_GENERIC_CBFS_UUID=y"; then
      echo "Configurable UUID not supported by the coreboot image"
      exit 7
    fi

    if uuidparse "${SYSTEM_UUID}" | grep -q "invalid"; then
      echo "Invalid UUID format"
      exit 8
    fi

    echo "Setting System UUID to ${_uuid}"
    echo -n "${_uuid}" > /tmp/system_uuid
    # We do not care if this one fails. It can fail if serial_number is not
    # already, there, which is fine.
    "${CBFSTOOL}" "${DASHARO_ROM}" remove -n system_uuid -r COREBOOT > /dev/null 2> /dev/null || true
    CBFSTOOL_ERR="$(${CBFSTOOL} ${DASHARO_ROM} add -f /tmp/system_uuid -n system_uuid -t raw -r COREBOOT 2>&1)"
    rm /tmp/system_uuid

    if echo "${CBFSTOOL_ERR}" | grep -q "The image will be left unmodified"; then
      echo "An error occurred when adding setting the UUID"
      echo "cbfstool output:"
      echo "${CBFSTOOL_ERR}"
      exit 9
    fi
    echo "Success"
  }

  set_serial_number() {
    local _serial="$1"

    if ! echo "${CB_CONFIG}" | grep -q "CONFIG_DRIVERS_GENERIC_CBFS_SERIAL=y"; then
      echo "Configurable Serial Number not supported by the coreboot image"
      exit 10
    fi

    echo "Setting Serial Number to ${_serial}"
    echo -n "$_serial" > /tmp/serial_number
    # We do not care if this one fails. It can fail if serial_number is not
    # already, there, which is fine.
    "${CBFSTOOL}" "${DASHARO_ROM}" remove -n serial_number -r COREBOOT > /dev/null 2> /dev/null || true
    CBFSTOOL_ERR="$(${CBFSTOOL} ${DASHARO_ROM} add -f /tmp/serial_number -n serial_number -t raw -r COREBOOT 2>&1)"
    rm /tmp/serial_number

    if echo "${CBFSTOOL_ERR}" | grep -q "The image will be left unmodified"; then
      echo "An error occurred when adding setting the Serial Number"
      echo "cbfstool output:"
      echo "${CBFSTOOL_ERR}"
      exit 11
    fi
    echo "Success"
  }

  if ! "${CBFSTOOL}" "${DASHARO_ROM}" extract -n config -r COREBOOT -f /tmp/cb_config > /dev/null 2> /dev/null; then
    echo "Failed to extract coreboot configuration from the image"
    exit 6
  fi

  CB_CONFIG="$(cat /tmp/cb_config)"
  rm /tmp/cb_config

  echo "Will modify ${DASHARO_ROM}"
  echo ""

  if [ -n "${SYSTEM_UUID}" ]; then
    set_uuid "${SYSTEM_UUID}"
  fi

  if [ -n "${SERIAL_NUMBER}" ]; then
    set_serial_number "${SERIAL_NUMBER}"
  fi

}

# :command.function
dcu_logo_command() {
  # src/logo_command.sh
  # SPDX-FileCopyrightText: 2023 3mdeb <contact@3mdeb.com>
  #
  # SPDX-License-Identifier: Apache-2.0

  # inspect_args

  DASHARO_ROM="${args[dasharo_rom_file]}"
  LOGO_FILE="${args[--logo]}"

  if [ ! -f "${LOGO_FILE}" ]; then
    echo "Logo file not found or invalid path."
    exit 12
  fi

  if ! file "${LOGO_FILE}" | grep -qE 'PNG image|JPEG image|Scalable Vector Graphics image|PC bitmap'; then
    echo "Invalid or unsupported logo file format"
    exit 13
  fi

  if ! "${CBFSTOOL}" "${DASHARO_ROM}" layout -w | grep -q "BOOTSPLASH"; then
    echo "BOOTSPLASH region not found"
    echo "Customizable logo not supported by the ${DASHARO_ROM} image"
    exit 14
  fi

  echo "Setting ${LOGO_FILE} as custom logo"
  convert -background None ${LOGO_FILE} BMP3:/tmp/logo.bmp
  # We do not care if this one fails. It can fail if serial_number is not
  # already, there, which is fine.
  "${CBFSTOOL}" "${DASHARO_ROM}" remove -n logo.bmp -r BOOTSPLASH > /dev/null 2> /dev/null || true
  CBFSTOOL_ERR="$(${CBFSTOOL} ${DASHARO_ROM} add -f /tmp/logo.bmp -r BOOTSPLASH -n logo.bmp -t raw -c lzma 2>&1)"
  rm /tmp/logo.bmp

  if echo "${CBFSTOOL_ERR}" | grep -q "too big"; then
    echo "Logo file too big to fit in the coreboot image"
    exit 15
  fi

  if echo "$CBFSTOOL_ERR" | grep -q "The image will be left unmodified"; then
    echo "An error occurred when adding the logo to coreboot image"
    exit 16
  fi

  echo "Success"

}

# :command.parse_requirements
parse_requirements() {
  # :command.fixed_flags_filter
  while [[ $# -gt 0 ]]; do
    case "${1:-}" in
      --version | -v)
        version_command
        exit
        ;;

      --help | -h)
        long_usage=yes
        dcu_usage
        exit
        ;;

      *)
        break
        ;;

    esac
  done

  # :command.dependencies_filter
  if command -v cbfstool >/dev/null 2>&1; then
    deps['cbfstool']="$(command -v cbfstool | head -n1)"
  else
    printf "missing dependency: cbfstool\n" >&2
    printf "%s\n" "You can build one from source code:
    https://github.com/Dasharo/dcu#compiling-cbfstool
  Or download and install pre-built version with following commands:
    sudo wget -O /usr/local/bin/cbfstool https://dl.3mdeb.com/open-source-firmware/utilities/cbfstool
    sudo chmod +x /usr/local/bin/cbfstool
  " >&2
    exit 1
  fi

  if command -v uuidparse >/dev/null 2>&1; then
    deps['uuidparse']="$(command -v uuidparse | head -n1)"
  else
    printf "missing dependency: uuidparse\n" >&2
    printf "%s\n" "Please install util-linux package" >&2
    exit 1
  fi

  if command -v convert >/dev/null 2>&1; then
    deps['convert']="$(command -v convert | head -n1)"
  else
    printf "missing dependency: convert\n" >&2
    printf "%s\n" "Please install imagemagick package" >&2
    exit 1
  fi

  # :command.command_filter
  action=${1:-}

  case $action in
    -*) ;;

    smbios | s)
      action="smbios"
      shift
      dcu_smbios_parse_requirements "$@"
      shift $#
      ;;

    logo | l)
      action="logo"
      shift
      dcu_logo_parse_requirements "$@"
      shift $#
      ;;

    # :command.command_fallback
    "")
      dcu_usage >&2
      exit 1
      ;;

    *)
      printf "invalid command: %s\n" "$action" >&2
      exit 1
      ;;

  esac

  # :command.parse_requirements_while
  while [[ $# -gt 0 ]]; do
    key="$1"
    case "$key" in

      -?*)
        printf "invalid option: %s\n" "$key" >&2
        exit 1
        ;;

      *)
        # :command.parse_requirements_case
        # :command.parse_requirements_case_simple
        printf "invalid argument: %s\n" "$key" >&2
        exit 1

        ;;

    esac
  done

}

# :command.parse_requirements
dcu_smbios_parse_requirements() {
  # :command.fixed_flags_filter
  while [[ $# -gt 0 ]]; do
    case "${1:-}" in
      --help | -h)
        long_usage=yes
        dcu_smbios_usage
        exit
        ;;

      *)
        break
        ;;

    esac
  done

  # :command.command_filter
  action="smbios"

  # :command.parse_requirements_while
  while [[ $# -gt 0 ]]; do
    key="$1"
    case "$key" in
      # :flag.case
      --uuid | -u)

        # :flag.case_arg
        if [[ -n ${2+x} ]]; then

          args['--uuid']="$2"
          shift
          shift
        else
          printf "%s\n" "--uuid requires an argument: --uuid, -u UUID" >&2
          exit 1
        fi
        ;;

      # :flag.case
      --serial-number | -s)

        # :flag.case_arg
        if [[ -n ${2+x} ]]; then

          args['--serial-number']="$2"
          shift
          shift
        else
          printf "%s\n" "--serial-number requires an argument: --serial-number, -s SERIAL" >&2
          exit 1
        fi
        ;;

      -?*)
        printf "invalid option: %s\n" "$key" >&2
        exit 1
        ;;

      *)
        # :command.parse_requirements_case
        # :command.parse_requirements_case_simple
        if [[ -z ${args['dasharo_rom_file']+x} ]]; then

          args['dasharo_rom_file']=$1
          shift
        else
          printf "invalid argument: %s\n" "$key" >&2
          exit 1
        fi

        ;;

    esac
  done

  # :command.required_args_filter
  if [[ -z ${args['dasharo_rom_file']+x} ]]; then
    printf "missing required argument: DASHARO_ROM_FILE\nusage: dcu smbios DASHARO_ROM_FILE [OPTIONS]\n" >&2
    exit 1
  fi

}

# :command.parse_requirements
dcu_logo_parse_requirements() {
  # :command.fixed_flags_filter
  while [[ $# -gt 0 ]]; do
    case "${1:-}" in
      --help | -h)
        long_usage=yes
        dcu_logo_usage
        exit
        ;;

      *)
        break
        ;;

    esac
  done

  # :command.command_filter
  action="logo"

  # :command.parse_requirements_while
  while [[ $# -gt 0 ]]; do
    key="$1"
    case "$key" in
      # :flag.case
      --logo | -l)

        # :flag.case_arg
        if [[ -n ${2+x} ]]; then

          args['--logo']="$2"
          shift
          shift
        else
          printf "%s\n" "--logo requires an argument: --logo, -l LOGO" >&2
          exit 1
        fi
        ;;

      -?*)
        printf "invalid option: %s\n" "$key" >&2
        exit 1
        ;;

      *)
        # :command.parse_requirements_case
        # :command.parse_requirements_case_simple
        if [[ -z ${args['dasharo_rom_file']+x} ]]; then

          args['dasharo_rom_file']=$1
          shift
        else
          printf "invalid argument: %s\n" "$key" >&2
          exit 1
        fi

        ;;

    esac
  done

  # :command.required_args_filter
  if [[ -z ${args['dasharo_rom_file']+x} ]]; then
    printf "missing required argument: DASHARO_ROM_FILE\nusage: dcu logo DASHARO_ROM_FILE [OPTIONS]\n" >&2
    exit 1
  fi

  # :command.required_flags_filter
  if [[ -z ${args['--logo']+x} ]]; then
    printf "missing required flag: --logo, -l LOGO\n" >&2
    exit 1
  fi

}

# :command.initialize
initialize() {
  version="0.2.1"
  long_usage=''
  set -e

  # src/initialize.sh
  # SPDX-FileCopyrightText: 2023 3mdeb <contact@3mdeb.com>
  #
  # SPDX-License-Identifier: Apache-2.0

  CBFSTOOL="cbfstool"

}

# :command.run
run() {
  declare -A args=()
  declare -A deps=()
  declare -a other_args=()
  declare -a input=()
  normalize_input "$@"
  parse_requirements "${input[@]}"

  case "$action" in
    "smbios") dcu_smbios_command ;;
    "logo") dcu_logo_command ;;
  esac
}

initialize
run "$@"
