#!/bin/bash
#XXX: should not depend on the host's bash ^

#################mo####### Download of sources using the "repo" command ########################
DL_LOG={{ instance_log_dir }}/cros_sources_dl.log
echo "getting Chromium OS sources..." >> $DL_LOG
{{ depot_tools_export_path_cmd }}
cd {{ cros_location }}
repo init -u https://chromium.googlesource.com/chromiumos/manifest.git -b {{ branch }} >> $DL_LOG
repo sync >> $DL_LOG

######################################## Build ##############################################
BOARDS="{{ boards_list }}"
for board in ${BOARDS}; do
  echo ${board}
  if [ ${board} == daisy ]; then
    echo "daisy board: accepting license for Mali drivers..."
    cros_sdk -- sudo sh -c "cp /etc/make.conf.user /etc/make.conf.user.save"
    cros_sdk -- sudo sh -c "echo 'ACCEPT_LICENSE=\"*\"' >> /etc/make.conf.user"
  fi
  
  {{ depot_tools_export_path_cmd }}
  cd {{ cros_location }}
  IMAGE_LOCATION=${board}.chromiumos.img
  NAYU_IMAGE_LOCATION=${board}.nayuos.img
  BUILD_LOG={{ instance_log_dir }}/cros_build.log
  
  # preparing packages (for chroot and image)
  date >> $BUILD_LOG
  echo "building packages for a ${board}-flavoured Chromium OS..." >> $BUILD_LOG
  cros_sdk -- ./build_packages --board=${board} >> $BUILD_LOG
  
  # Chromium original dev image
  date >> $BUILD_LOG
  echo "building image for a ${board}-flavoured Chromium OS..." >> $BUILD_LOG
  cros_sdk -- ./build_image --board=${board} >> $BUILD_LOG \
    && echo "removing old image if any and creating image file $IMAGE_LOCATION..." >> $BUILD_LOG \
    && cros_sdk -- rm -f $IMAGE_LOCATION && cros_sdk -- touch $IMAGE_LOCATION \
    && cros_sdk -- cros flash --board=${board} file://$IMAGE_LOCATION >> $BUILD_LOG
  
  # NayuOS
  date >> $BUILD_LOG
  echo "rebuilding image with noenable_rootfs_verification and modifying image" >> $BUILD_LOG
  cros_sdk -- ./build_image --noenable_rootfs_verification --board=${board} >> $BUILD_LOG \
    && echo "modifying image, removing old image if any and creating image file $NAYU_IMAGE_LOCATION..." >> $BUILD_LOG \
    && cros_sdk -- ./modify_image.sh ${board} \
    && cros_sdk -- rm -f $NAYU_IMAGE_LOCATION && cros_sdk -- touch $NAYU_IMAGE_LOCATION \
    && cros_sdk -- cros flash --board=${board} file://$NAYU_IMAGE_LOCATION >> $BUILD_LOG
  
  if [ ${board} == daisy ]; then
    echo "daisy board: removing accepted license for the next builds..."
    cros_sdk -- sudo sh -c "cp /etc/make.conf.user.save /etc/make.conf.user"
  fi
done
exit 0