#!/bin/bash

#
# File .......... swuk_petalinux-build
# Author ........ Steve Haywood
# Website ....... http://www.spacewire.co.uk
# Project ....... Common (SpaceWire UK Tutorial)
# Date .......... 25 Jun 2025
# Version ....... 2.0
# History .......
#   1.0 common/other/src/script/petalinux-build-id.sh
# Description ...
#   Script to read product identification file, obtain GIT repository
# information, append project identification file with GIT information, build
# PetaLinux project and then restore project identification file.
#

# Strict
#set -euo pipefail


################################################################################
# Main function.
# Arguments ...... ${@}
# Return ......... None
# Exit code ...... Status (0=success, 1=failure)
# Shared (In) .... None
# Shared (Out) ... None
main()
{
  # Declare constants
  local -r  c_opthelp="--help"  # Str: Help option name
  local -Ar c_options=(         # ARR: Options & associated help information
    [${c_opthelp}]="Display this help and exit."
  )
  local -ar c_optorder=(        # Arr: Help options display order
    ${c_opthelp}
  )
  local -ar argv=(${@})         # Arr: Get argument values (space-separated) into array
                                # Str: Project identification file
  local -r  c_project="project-spec/meta-user/recipes-apps/website/files/project.txt"

  # Declare variables
  local     arg                 # Str: Current argument from argv array
  local     option              # Str: Current option from c_optorder array
  local -a  ids                 # Arr: Product identification (Description, Company, Author)
  local     id_timestamp        # Str: GIT timestamp
  local     id_hash             # Str: GIT hash
  local     id_append           # Str: Version appendage
  local     status              # Str: GIT status

  # Display help information
  if [[ " ${argv[*]} " =~ " ${c_opthelp} " ]]; then
    echo "Usage: $(basename ${0}) [OPTION]..."
    echo "Build a PetaLinux project that incorporates the product identification along with the GIT repository information."
    echo
    for option in ${c_optorder[@]}
    do
      echo "      ${option} $(printf ' %.0s' {1..12} | head -c $((12-${#option}))) ${c_options[${option}]}"
    done
    echo
    exit 0
  fi

  # Get & check the arguments
  for arg in ${argv[@]}; do
    if [[ ${arg:0:2} == "--" ]]; then  # Option
      [[ ! -v c_options[${arg}] ]] &&
        echo "Option (${arg}) is not recognised!" >&2 &&
        exit 1
    else
      echo "Too many arguments found, expecting 0!" >&2
      exit 1
    fi
  done

  # Only perform bulk of actions if identification file exists
  if [ -f "${c_project}" ]; then

    # Read project identification file
    readarray -t ids < "${c_project}"

    # Display project identification information
    echo -e '\033[1mNOTE\033[0m: Building PetaLinux with the following identification'
    echo "Description ... ${ids[0]}"
    echo "Company ....... ${ids[1]}"
    echo "Author ........ ${ids[2]}"

    # Get GIT timestamp
    id_timestamp=$(git log -1 --pretty=%cd --date=format:"%d-%b-%Y - %H:%M:%S")
    if [ $? -ne 0 ]; then
      id_timestamp="00-Xxx-0000 - 00:00:00"
    fi

    # Get GIT hash
    id_hash=$(git log -1 --pretty=%H)
    if [ $? -ne 0 ]; then
      id_hash="0000000000000000000000000000000000000000"
    fi

    # Get GIT status
    id_append=""
    status=$(git status -s)
    if [ $? -ne 0 ]; then
      id_append="(undefined)"
    else
      if [ ! -z "${status}" ]; then
        id_append="(unstaged)"
      else
        status=$(git branch -r --contains ${id_hash})
        if [ $? -ne 0 ]; then
          id_append="(undefined)"
        else
          if [ -z "${status}" ]; then
            id_append="(unpushed)"
          fi
        fi
      fi
    fi

    # Display project identification information
    echo "Version ....... ${ids[3]} ${id_append}"
    echo "Timestamp ..... ${id_timestamp}"
    echo "Hash .......... ${id_hash}"

    # Modify project identification file
    echo ${ids[0]}               > ${c_project}  # Description
    echo ${ids[1]}              >> ${c_project}  # Company
    echo ${ids[2]}              >> ${c_project}  # Author
    echo ${ids[3]} ${id_append} >> ${c_project}  # Version
    echo ${id_timestamp}        >> ${c_project}  # Timestamp
    echo ${id_hash}             >> ${c_project}  # Hash

    # Build PetaLinux
    $(which petalinux-build)
    jobs -l
    wait

    # Restore project identification file
    echo ${ids[0]}  > ${c_project}  # Description
    echo ${ids[1]} >> ${c_project}  # Company
    echo ${ids[2]} >> ${c_project}  # Author
    echo ${ids[3]} >> ${c_project}  # Version

  else

    # Build PetaLinux
    $(which petalinux-build)

  fi
}


################################################################################
# Opening gambit.
# Arguments ...... ${@}
# Return ......... None
# Exit code ...... Status (0=success, 1=failure)
# Shared (In) .... None
# Shared (Out) ... None
main ${@}
exit 0
