#!/bin/bash

if [ $# -ne 1 ]; then
    printf "createarchive\n"
    printf "usage: createarchive <folder to be archived>\n"
    printf "warning: the archive will be moved to "backups" directory (`echo $dest`)\n"
    exit 1
fi


# what this does in short: tar, compress, timestamp, shred the tar, mv .xz to pwd and display it
logdate="$(date +%Y%m%dT%H%M%S)"
basedir="$1"
tmpdir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXX")
#/run/user/$(id -u) tmpfs 0700 perms
f="`cd $basedir; pwd | tr '/' ' ' | sed 's/^.* / /' | cut -c2-`" > /dev/null
g="$logdate-$f.tar"
dest=~/MEGA/Private/backups

doathing() {
    cd $basedir/..
    tar cfv "$tmpdir/$g" "$f" && \
    xz -vzk9e "$tmpdir/$g" -S .xz && \
    rsync -avP "$tmpdir/$g.xz" "$dest" && \
    shred -zuv "$tmpdir/$g" "$tmpdir/$g.xz" && \
    printf "\n"
    ls -latr "$dest/$g.xz"
}

if [ ! -d $1 ]; then
    echo "$1 is not a directory"
    exit 1
else
    echo `pwd`
    echo "$f"
    echo "$1"

    doathing
    trap "rm -rfv $tmpdir" 0 1 3 15
    exit $?
fi
