#!/bin/bash
# Super Grub Disk - grub-build-002-clean-and-update
# Copyright (C) 2009,2010,2011,2012,2013,2014,2015  Adrian Gibanel Lopez.
#
# Super Grub Disk 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.
#
# Super Grub Disk 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 Super Grub Disk.  If not, see <http://www.gnu.org/licenses/>.

# Grub2 Build for Super Grub2 Disk - Clean build dir and update (pull)

SG2D_DIR="$(pwd)"

# Git check

if git --version > /dev/null 2>&1 ; then
  :
else
  echo -e -n "Git was not found. Git is needed\n";
  echo -e -n "Aborting\n";
  exit 3

fi

source grub-build-config

# Check if build directories exists or not.
# If anyone of them does not exist exit with an error.

for n_build_dir in "${!SG2D_GRUB_BUILD_DIRS_ARR[@]}"; do

  if [ ! -d "${SG2D_GRUB_BUILD_DIRS_ARR[n_build_dir]}" ] ; then
    echo -e -n "Clean and build refuses to continue\n";
    echo -e -n "'${SG2D_GRUB_BUILD_DIRS_ARR[n_build_dir]}' does not exist\n";
    echo -e -n "Have you run: ./grub-build-001-prepare-build ?\n";
    exit 2
  fi

done

for n_build_dir in "${!SG2D_GRUB_BUILD_DIRS_ARR[@]}"; do
  cd "${SG2D_GRUB_BUILD_DIRS_ARR[n_build_dir]}"
  # Reset git to have a clean state
  git reset --hard
  git clean -f -d
  git clean -f -x -d
  # Checkout master so that we can pull last version
  git checkout master
  # Pull last version just in case we are requesting a new commit
  # not found or our local copy of git
  git pull
  # Finally checkout the requested commit
  git checkout "${GRUB2_COMMIT}"
  # prepare the locales
  ./linguas.sh
done


cd "${SG2D_DIR}"
