#!/bin/bash

source /var/roothome/app/bin/home/shared.sh

dow=$(date +%u)                                                          # current day of week number.
path_src="/var/mnt/storage/hot"                                          # backup src location.
path_media="/var/mnt/storage/cold_1/media /var/mnt/storage/cold_2/media" # media paths.
path_mount="/var/mnt/backup"                                             # backup mount location.
path_backup="$path_mount/backup"                                         # backup dir location.
path_docker="$path_backup/home"                                          # docker backup location.

# check if backup drive is mounted.
if [ ! -f "$path_mount"/.mount ]; then
  echo "backup : $path_mount not mounted"
  notify "backup : $path_mount not mounted"
  exit 1
fi

# check if hot storage is mounted.
if [ ! -f "$path_src"/.mount ]; then
  echo "backup : $path_src not mounted"
  notify "backup : $path_src not mounted"
  exit 1
fi

# tweak bash.
shopt -s globstar
shopt -s dotglob

# cd to src storage.
builtin cd "$path_src"

# save media list.
/usr/bin/find $path_media -type d | gzip -1 > media/list/cold.txt.gz || notify 'backup : save media list failed'

# backup docker.
rm $path_docker/${dow}_*.tar.gz
/usr/bin/tar --exclude-from=docker/.tarignore -c docker | /usr/bin/gzip -1 > $path_docker/docker.tar.gz && mv $path_docker/docker.tar.gz $path_docker/${dow}_$(/usr/bin/sha1sum $path_docker/docker.tar.gz | cut -d\  -f1).tar.gz || notify 'backup : docker failed'

# copy media.
/usr/bin/rsync -a --delete /var/mnt/storage/hot/media/music/  /var/mnt/backup/backup/music/  || notify 'backup : copy music failed'
/usr/bin/rsync -a --delete /var/mnt/storage/hot/media/book/   /var/mnt/backup/backup/book/   || notify 'backup : copy book failed'
/usr/bin/rsync -a --delete /var/mnt/storage/hot/media/porn/   /var/mnt/backup/backup/porn/   || notify 'backup : copy porn failed'
/usr/bin/rsync -a --delete /var/mnt/storage/hot/media/family/ /var/mnt/backup/backup/family/ || notify 'backup : copy family failed'
/usr/bin/rsync -a --delete /var/mnt/storage/hot/media/paper/  /var/mnt/backup/backup/paper/  || notify 'backup : copy paper failed'
/usr/bin/rsync -a --delete /var/mnt/storage/hot/media/list/   /var/mnt/backup/backup/list/   || notify 'backup : copy list failed'

# upload external.
#/usr/bin/rsync -ahP -e 'ssh -p 143 -i /var/roothome/document/key/ssh/pi.key' /var/mnt/backup/ root@192.168.1.6:/var/mnt/backup/ || notify 'backup : failed upload'

# notify completion & size.
bupsize=$(/usr/bin/du -h $path_docker/${dow}_*.tar.gz | awk '{print $1}')
notify_silent "backup : complete : $bupsize"
echo "backup : complete : $bupsize"