#!/bin/bash

LOGFILENAME="duplicity_docker_backup.log"
LOGDIR="/mnt/user/logs/Duplicity/${LOGFILENAME}"
scriptname="duplicity_docker_backup.sh"
# check if we are the only local instance
if [[ "`pidof -x ${scriptname} -o %PPID`" ]]; then
        echo "This script is already running with PID `pidof -x $(basename $0) -o %PPID`" >> "${LOGDIR}"
        exit
fi
 

# start your script here
#SRCNAMES="calibre-cops calibre-desktop calibre-web chrome cloudcmd filezilla firefox guacamole mailpile my_bookmarks netdata plex portainer traefik unifi xeoma"
SRCNAMES="calibre-cops"
#SRCNAMES=$(docker ps -a -q --format "{{.Names}}"
#SRCNAMES="Apps"
VERBOSITY=4
SRCDIR="/mnt/disks/nvme1/appdata"
DOCKERDIR="${SRCDIR}/duplicity_docker_backup"
CACHEDIR="${DOCKERDIR}/.cache:/home/duplicity/.cache/duplicity"
ARCHIVEDIR="${DOCKERDIR}/archive"
DSTDIR="/mnt/user/Google/gdrive/Backup/Ket/Duplicity/appdata"
KEYDIR="${DOCKERDIR}/.gnupg:/home/duplicity/.gnupg"
BOTODIR="${DOCKERDIR}/.boto:/home/duplicity/.boto:ro"
PASSPHRASE="fjK8UH3hVvNimTvkmMMt7DhesJ"

for SRCNAME in $SRCNAMES
do
  echo " " >> "${LOGDIR}"
  echo "****************************************************" >> "${LOGDIR}"
  echo "$(date "+%d/%m/%Y %T") Starting ${SRCNAME} Backup" >> "${LOGDIR}"
  echo "****************************************************" >> "${LOGDIR}"
  echo " " >> "${LOGDIR}"
  
  echo "Stoping container ${SRCNAME}" >> "${LOGDIR}"
  docker stop ${SRCNAME}
  sleep 20
  docker run --rm \
-v "${SRCDIR}/${SRCNAME}:/src:ro" \
-v "${DSTDIR}/${SRCNAME}:/dst" \
-v "${ARCHIVEDIR}:/archive" \
-v "${CACHEDIR}" \
-v "${KEYDIR}" \
-v "${BOTODIR}" \
-v "${LOGDIR}:/logs" \
-v "/etc/localtime:/etc/localtime:ro" \
-e "TZ=Europe/Paris" \
-e "PASSPHRASE=${PASSPHRASE}" \
wernight/duplicity duplicity incr \
--allow-source-mismatch \
--full-if-older-than=6M \
--log-file "/logs" \
--verbosity ${VERBOSITY} \
--name="${SRCNAME}" \
--archive-dir="/archive" \
/src file://dst

echo "Starting container ${SRCNAME}" >> "${LOGDIR}"
  docker start ${SRCNAME}

  echo "****************************************************" >> "${LOGDIR}"
  echo "$(date "+%d/%m/%Y %T") End ${SRCNAME} Backup" >> "${LOGDIR}"
  echo "****************************************************" >> "${LOGDIR}"
  echo " " >> "${LOGDIR}"
done

