#!/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
#

set -e

DPNS_IMAGES=()
DPNS_DUMPDIR=/srv/docker/images
DPNS_REMOUNT=1
DPNS_PRUNE=1
DPNS_CONFIG="${DPNS_CONFIG:-/etc/dpns/dpns.conf}"
. "${DPNS_CONFIG}"

if [ "${#DPNS_IMAGES[*]}" = "0" ]; then
  echo "Empty image list, nothing to do!"
  exit 0
fi

set +e

if [ "$DPNS_REMOUNT" == "1" ]; then
  if findmnt -n --raw --output=options -fT "$DPNS_DUMPDIR" | egrep -q '(^|\W)ro(\W|$)'; then
    target=$(findmnt -n --raw --output=target -fT "$DPNS_DUMPDIR")

    function remnt {
      echo "Remounting $target read-only..."
      mount "$target" -o remount,ro || true
    }
    trap remnt exit

    echo "Remounting $target read-write..."
    mount "$target" -o remount,rw
    echo
  fi
fi

images=()
for image in ${DPNS_IMAGES[*]}; do
  echo "Updating $image..."
  docker pull "$image"
  img="$(echo $image | sha1sum | cut -f1 -d' ').tar"
  images+=($img)
  docker save -o "$DPNS_DUMPDIR/$img" "$image" && echo "Saved: $img"
  echo
done

if [ "$DPNS_PRUNE" != "1" ]; then
  exit 0
fi

set -e

echo "Checking for obsolete image dumps..."
cd "$DPNS_DUMPDIR"
for oimg in *.tar; do
  obsolete=1
  for nimg in ${images[*]}; do
    if [ "$oimg" = "$nimg" ]; then
      obsolete=0
    fi
  done
  if [ "$obsolete" = "1" ]; then
    rm -f "$oimg"
    echo " Purged: $oimg"
  fi
done
