#!/bin/bash

set -e

dpkg -s gcc-aarch64-linux-gnu > /dev/null 2>&1 ||
{
  read -rp "AArch64 compiler not found, install it now? " yn
  case $yn in
    [Yy]* ) sudo apt install -y gcc-aarch64-linux-gnu;;
    [Nn]* ) exit;;
    * ) echo "Please answer yes or no";;
  esac;
}

dpkg -s swig > /dev/null 2>&1 ||
{
  read -rp "Simplified Wrapper and Interface Generator not found, install it now? " yn
  case $yn in
    [Yy]* ) sudo apt install -y swig;;
    [Nn]* ) exit;;
    * ) echo "Please answer yes or no";;
  esac;
}

dpkg -s python-dev-is-python2 > /dev/null 2>&1 ||
{
  read -rp "Python (2) development headers not found, install them now? " yn
  case $yn in
    [Yy]* ) sudo apt install -y python-dev;;
    [Nn]* ) exit;;
    * ) echo "Please answer yes or no";;
  esac;
}

dpkg -s device-tree-compiler > /dev/null 2>&1 ||
{
  read -rp "Device Tree Compiler not found, install it now? " yn
  case $yn in
    [Yy]* ) sudo apt install -y device-tree-compiler;;
    [Nn]* ) exit;;
    * ) echo "Please answer yes or no";;
  esac;
}

[ -e arm-trusted-firmware.git ] || tar -xf arm-trusted-firmware.git.tar.bz2
[ -e arm-trusted-firmware ]     || git clone arm-trusted-firmware.git
[ -e u-boot.git ]               || tar -xf u-boot.git.tar.bz2
[ -e u-boot ]                   || git clone u-boot.git
[ -e u-boot/A64Env ]            || cp A64Env u-boot

export CROSS_COMPILE=aarch64-linux-gnu-
unset CFLAGS CXXFLAGS CPPFLAGS LDFLAGS
(
  cd arm-trusted-firmware
  make PLAT=sun50i_a64 DEBUG=1 bl31
  cp build/sun50i_a64/debug/bl31.bin ../u-boot
)
(
  cd u-boot
  make distclean
  make pinebook_defconfig
  echo 'CONFIG_IDENT_STRING=" RISC OS"' >> .config
  echo 'CONFIG_USE_DEFAULT_ENV_FILE=y' >> .config
  echo 'CONFIG_DEFAULT_ENV_FILE="./A64Env"' >> .config
  make EXTRAVERSION=-
  cat spl/sunxi-spl.bin u-boot.itb > u-boot-sunxi-with-spl-pinebook.bin
  cat spl/sunxi-spl.bin u-boot.itb > mguboot
)
