#!/bin/sh
repository=$(grep repository config/settings.cfg | sed s/repository=//)
echo "Fetching bootloader files from $repository"

remote=0
case $repository in
  ftp:* | http:* | https:* ) remote=1;;
esac

# Remove old files
rm -rf bootloader
mkdir bootloader

archs="i686 x86_64"
for arch in $archs; do
  echo "Searching $arch/media/core/updates"
  rpm_list=$(urpmq --use-distrib $repository/$arch --media "Core Updates" --exclude-media "Debug,Testing" --curl-options "-s" --wget-options "-q" -r drakiso-bootloader-files)
  rpm_name=${rpm_list##*|}
  media=core/updates
  if [ -z $rpm_name ] ; then
    echo "Searching $arch/media/core/release"
    rpm_list=$(urpmq --use-distrib $repository/$arch --media "Core Release" --exclude-media "Debug,Testing" --curl-options "-s" --wget-options "-q" -r drakiso-bootloader-files)
    rpm_name=${rpm_list##*|}
    media=core/release
  fi
  if [ -z $rpm_name ] ; then
    echo "ERROR: couldn't find $arch drakiso-bootloader-files RPM in $repository."
    exit 1
  else
    echo "Extracting $arch bootloader files from repository."
    if [ $remote -eq 1 ] ; then
      wget -q $repository/$arch/media/$media/$rpm_name.$arch.rpm
      if [ $? -ne 0 ] ; then
        echo "ERROR: failed to download RPM from archive."
        exit 1
      fi
      path=$rpm_name.$arch.rpm
    else
      path=$repository/$arch/media/$media/$rpm_name.$arch.rpm
    fi
    rpm2cpio $path | cpio -idm --quiet
    if [ $? -ne 0 ] ; then
      echo "ERROR: failed to extract files from archive."
      exit 1
    fi
    if [ $remote -eq 1 ] ; then
      rm $path
    fi
  fi
  cp -ru usr/share/drakiso/bootloader/* bootloader
  rm -r usr
done
