#!/bin/bash
# Super Grub Disk - supergrub-sourcecode
# Copyright (C) 2017  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/>.

SUPER_GRUB2_DISK_FILE_PREFIX="super_grub2_disk"

SGD2_SOURCE_DIR="$(pwd)"
SG2D_DIR="${SGD2_SOURCE_DIR}"


function build_sourcecode () {

  SOURCE_CODE_FILENAME="${SUPER_GRUB2_DISK_FILE_PREFIX}\
_${sgrub_version}_source_code.tar.gz"
  git archive $(git rev-parse --abbrev-ref HEAD) | gzip -c > "${SG2D_SOURCECODE_DIR}/${SOURCE_CODE_FILENAME}"

  generate_filename_hashes "${SG2D_SOURCECODE_DIR}/${SOURCE_CODE_FILENAME}"

  PRE_LOOP_DIR="$(pwd)"
  for nefiplatform in ${SG2D_SECUREBOOT_EFI_PLATFORMS} ; do
    cd ${SG2D_SECUREBOOT_BINARIES_DIR}/vendor
    for nvendor in * ; do
      if [ -e "${nvendor}/shim${nefiplatform}-sourcecode.tar.gz" ] ; then
        cp "${nvendor}/shim${nefiplatform}-sourcecode.tar.gz" "${SG2D_SOURCECODE_DIR}/shim${nefiplatform}-${nvendor}-sourcecode.tar.gz"
        cp "${nvendor}/grub${nefiplatform}-sourcecode.tar.gz" "${SG2D_SOURCECODE_DIR}/grub${nefiplatform}-${nvendor}-sourcecode.tar.gz"
        generate_filename_hashes "${SG2D_SOURCECODE_DIR}/shim${nefiplatform}-${nvendor}-sourcecode.tar.gz"
        generate_filename_hashes "${SG2D_SOURCECODE_DIR}/grub${nefiplatform}-${nvendor}-sourcecode.tar.gz"
      fi
    done
  done

  cd "${PRE_LOOP_DIR}"

}


# Needed for getting SG2D version
source menus/sgd/version.cfg

source grub-build-config

# Get common library for supergrub-mk commands
source supergrub-mkcommon

SG2D_RELEASE_DIR="${SGD2_SOURCE_DIR}/releases/${sgrub_version}"
SG2D_ISO_RELEASE_DIR="${SG2D_RELEASE_DIR}/super_grub2_disk_${sgrub_version}"
SG2D_SOURCECODE_DIR="${SG2D_ISO_RELEASE_DIR}/source_code"

if [ ! -d "${SG2D_SOURCECODE_DIR}" ] ; then
  mkdir --parents "${SG2D_SOURCECODE_DIR}"
fi

build_sourcecode
