#!/bin/sh


# Zerocat Coreboot Machines --- Create very satisfying free software devices.
#
# Copyright (C) 2021, 2022  Kai Mertens <kmx@posteo.net>
#
# This file is part of Zerocat Coreboot Machines.
#
# Zerocat Coreboot Machines is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Zerocat Coreboot Machines is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with Zerocat Coreboot Machines.  If not, see <http://www.gnu.org/licenses/>.


# Usage
# =====
#
# grub-mkconfig-coreboot-guix.sh
#
# Turn GNU Guix System’s standard /boot/grub/grub.cfg into
# /boot/grub/coreboot_grub.cfg which helps you to start Zerocat Machines


# functions
no_tool() {
  # $1 = tool name
  # let’s use builtin echo command here:
  echo "Tool $1 is missing."
  exit 1
}
check_perm() {
  if [ $EUID -ne 0 ]; then
    $ECHO "This script must be run with priviledges."
    exit 1
  fi
}
main() {
  # tools
  SED=$(command -v sed) || no_tool 'sed'
  ECHO=$(command -v echo) || no_tool 'echo'
  DATE=$(command -v date) || no_tool 'date'
  CHMOD=$(command -v chmod) || no_tool 'chmod'

  # data
  IN=/boot/grub/grub.cfg
  OUT=/boot/grub/coreboot_grub.cfg
  STAMP="[ $($DATE -Is) ]:"
  MSG_STAMP="Modified to match Zerocat boot procedure!"
  DELAY=2
  MSG_DELAY="Using text mode terminal as fallback."
  INDENT="  "

  # check file $IN
  [ -f "$IN" ] || {
    $ECHO "File $IN does not exist."
    exit 1
  }

  # check file $OUT
  [ -f "$OUT" ] && {
    $ECHO "File $OUT exists."
    exit 1
  }

  # check permissions
  check_perm

  # create file
  $SED -r \
    -e "1i# ${STAMP} ${MSG_STAMP}" \
    -e '1i#' \
    -e "/# Localization/s/^/\n/;" \
    -e "/if background_image/,/fi/{;s/else/&\n${INDENT}echo \"${MSG_DELAY}\"\n${INDENT}sleep ${DELAY}/;};" \
    -e "/if loadfont/,/terminal_output/s/^/${INDENT}/;" \
    -e '/if loadfont/iif [ "${grub_platform}" != coreboot ]; then' \
    -e '/terminal_output/afi' \
    -e "/set locale_dir/,/set lang/s/^/${INDENT}/;" \
    -e '/set locale_dir/iif [ "${grub_platform}" != coreboot ]; then' \
    -e '/set lang/afi' \
    $IN > $OUT || {
      $ECHO "Could not write file $OUT."
      exit 1
    }

  # change access permissions
  $CHMOD -wx $OUT || {
    $ECHO "Could not set file permissions."
    exit 1
  }

  # success
  $ECHO "File $OUT successfully written."

}

# start
main "$@"
