#!/bin/bash

# dpns - docker pull & save
#
# Authors:
#   Thomas Liske <thomas@fiasko-nw.net>
#
# Copyright Holder:
#   2018 - 2020 (C) Thomas Liske [https://github.com/liske/dpns]
#
# License:
#   This program 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 2 of the License, or
#   (at your option) any later version.
#
#   This program 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 this package; if not, write to the Free Software
#   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

DPNS_PNAME=/var/run/docker.sock
DPNS_PWAIT=100
DPNS_IMAGES=()
DPNS_DUMPDIR=/srv/docker/images
DPNS_CONFIG="${DPNS_CONFIG:-/etc/dpns/dpns.conf}"
. "${DPNS_CONFIG}"

if [ "${#DPNS_IMAGES[*]}" = "0" ]; then
  echo "Empty image list."
  exit 0
fi

if [ ! -e "$DPNS_PNAME" ]; then
  echo "Waiting for $DPNS_PNAME..."
  while [ "$DPNS_PWAIT" -gt 0 -a ! -e "$DPNS_PNAME" ]; do
          DPNS_PWAIT=$((DPNS_PWAIT - 1))
          sleep .1
  done
  echo
fi

for image in ${DPNS_IMAGES[*]}; do
  img="$(echo $image | sha1sum | cut -f1 -d' ').tar"
  docker load -i "$DPNS_DUMPDIR/$img"
  echo
done
