#!/bin/bash
# a-b-c: a uboot boot.scr script generator
#
# Usage:
# a-b-c
#
# Copyright 2013 Red Hat, Inc.  All rights reserved.
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

VERSION=0.56

PATH=/sbin:/bin:$PATH

set -e

ARCH="`/usr/bin/uname -m`"
case $ARCH in
  arm*)
    ;;
  *) echo "a-b-c does not support $ARCH architecture"
     exit 1
    ;;
esac

[ -f /etc/sysconfig/arm-boot-config ] && . /etc/sysconfig/arm-boot-config
[ -f /etc/sysconfig/uboot ] && . /etc/sysconfig/uboot
[ -f /etc/vconsole.conf ] && . /etc/vconsole.conf
[ -f /etc/locale.conf ] && . /etc/locale.conf

: ${UBOOT_DIR:="/boot"}
: ${UBOOT_KLIST:="$UBOOT_DIR/klist.txt"}

if [ ! -f $UBOOT_KLIST ]; then
  echo Could not find $UBOOT_KLIST, exiting
  exit 1
fi

if [ "X$ABCBOOT_ARGS" = X ]; then ABCBOOT_ARGS="rhgb quiet"; fi
if [ "X$FONT" != X ]; then ABCBOOT_ARGS="$ABCBOOT_ARGS FONT=$FONT"; fi
if [ "X$KEYMAP" != X ]; then ABCBOOT_ARGS="$ABCBOOT_ARGS KEYMAP=$KEYMAP"; fi
if [ "X$LANG" != X ]; then ABCBOOT_ARGS="$ABCBOOT_ARGS LANG=$LANG"; fi
if [ "X$UBOOT_ARGS" != X ]; then ABCBOOT_ARGS="$ABCBOOT_ARGS UBOOT_ARGS=$UBOOT_ARGS"; fi

optecho=/usr/bin/true

while [ $# -ne 0 ]; do
  option=$1
  shift

  case $option in
  --*=*) optarg=`echo $option | sed -e 's/^[^=]*=//'`
    ;;
  esac

  case $option in
  --x) set -x
    ;;
  --debug) optecho=/usr/bin/echo
    ;;
  *) echo "$0: Invalid argument \"$option\""
     exit 1
    ;;
  esac
done


date="`date`"
###############################

# This should actually use $UBOOT_DIR
cd $UBOOT_DIR
cat << EOF > boot.cmd.$$
# mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n "a-b-c on $date" -d boot.cmd boot.scr
echo Welcome to a-b-c $VERSION.
echo

EOF

for i in /etc/a-b-c.d/*; do
  case $i in
  *.rpmsave) ;;
  *.rpmnew)
    echo "Skipping $i, this might be a problem." ;;
  *)
    $optecho "echo Beginning section from $i" >> boot.cmd.$$
    . $i >> boot.cmd.$$ || failed=1
    if [ X$failed != X ]; then
      echo $i produced an error, check $UBOOT_DIR/boot.cmd.$$ for details
      exit 1
    fi ;;
  esac
done

mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n "a-b-c on $date" -d boot.cmd.$$ boot.scr.$$ >& /dev/null

if [ -f boot.scr ]; then mv -f boot.scr boot.scr.old; fi
if [ -f boot.cmd ]; then mv -f boot.cmd boot.cmd.old; fi
mv -f boot.cmd.$$ boot.cmd
mv -f boot.scr.$$ boot.scr

