#!/bin/bash
trap 'error_handler $? $LINENO $BASH_COMMAND' ERR
error_handler() {
  echo "Error: $3 return ($1) occurred on $2" >>error-$tm.log
}

require_file=${1:-"deb.list"}
deb_list=$(cat $require_file)
tm=$(date +%Y%m%d)

DEB_DIR=deb-$tm
mkdir -p ${DEB_DIR}
chown _apt ${DEB_DIR}
(
cd ${DEB_DIR}
for f in $deb_list; do
  apt-get download $f
  if [ "$?" != "0" ]; then
    echo $f >>../fail-$tm.list
  fi
done
cp -p ../grafana/* .
dpkg-scanpackages -m . > Packages
)
DEB_TGZ=${DEB_DIR}.tgz
rm -rf ${DEB_TGZ}
tar cvfz ${DEB_TGZ} ${DEB_DIR}
rm -rf deb.tgz
ln -s ${DEB_TGZ} deb.tgz
