#!/bin/sh
# description "synchronizes kernel module"
# author "Scaleway <opensource@scaleway.com>"

set -e

DIR=/lib/modules
mkdir -p $DIR
TMP_DIR=`mktemp -d -p $DIR`
KVERSION=`uname -r`
TIMEOUT=10

export PATH="${PATH:+$PATH:}/usr/bin:/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin"

clean() {
    rm -rf "$TMP_DIR" 2>/dev/null
}
trap 'clean' INT TERM EXIT

if [ ! -d $DIR/${KVERSION} ]
then
  # TODO: replace wget with rsync
  # optional: add this line to remove empty modules (happens sometime)
  # find . -name "*.ko" -size 0 -delete
  wget --timeout=${TIMEOUT} --quiet --no-check-certificate -r --no-parent \
     --reject "index.html*" --reject "robots.txt" \
     --no-host-directories --cut-dirs 3 --directory-prefix \
     $TMP_DIR http://mirror.scaleway.com/kernel/${KVERSION}/modules/${KVERSION}/

  if [ $? -eq 0 ]
  then
    mkdir -p $DIR/${KVERSION}
    mv $TMP_DIR/${KVERSION} $DIR
  fi
fi
