#!/bin/bash
unset HISTFILE
export AWS_ACCESS_KEY_ID={{ wasabi_access_key_id }}
export AWS_SECRET_ACCESS_KEY={{ wasabi_secret_access_key }}
export RESTIC_REPOSITORY={{ restic_repository }}
export RESTIC_PASSWORD={{ restic_password }}
RUN_OPTION=$1
if ([ -z "$(restic cat config)" ]) 2>/dev/null; then
    restic init
fi
docker-compose up -d
CONTAINERS=$(grep container_name: ./docker-compose.yml | sed 's/^.*: //')
docker-compose stop
if [ ! -f .git-cache-meta ]; then
    git-cache-meta --store
fi
if [ -f .env ]; then
    COMPOSE_PROJECT_NAME=$(grep COMPOSE_PROJECT_NAME .env | xargs)
    COMPOSE_PROJECT_NAME=${COMPOSE_PROJECT_NAME#*=}
fi
FOLDER_NAME="${PWD##*/}"
FOLDER_NAME=${FOLDER_NAME,,}
if [ -z "$COMPOSE_PROJECT_NAME" ]; then
    echo "Setting project name using directory name"
    PROJECT_NAME=$FOLDER_NAME
else
    echo "Setting project name using .env file"
    PROJECT_NAME=$COMPOSE_PROJECT_NAME
fi
echo "Detected project name: $PROJECT_NAME"
# Backup volumes
VOLUMES=$(docker volume ls -f name=$PROJECT_NAME --format "{% raw %}{{.Name}}{% endraw %}")
for i in ${VOLUMES[@]}
do
    if [ "$RUN_OPTION" == 'restore' ]; then
        echo "Restoring volume named $i from $i.tar.bz2"
        restic restore $(restic snapshots | grep $i.tar.bz2 | tail -1 | awk '{print $1}') --target .
        cat $i.tar.bz2 | docker run -i -v $i/volume --rm loomchild/volume-backup restore -
        rm $i.tar.bz2
        git-cache-meta --apply
    else
        echo "Backing up volume named $i to $i.tar.bz2"
        docker run -v $i:/volume -v /tmp:/backup --rm loomchild/volume-backup backup -> $i.tar.bz2
        restic backup $i.tar.bz2
        rm $i.tar.bz2
        git-cache-meta --store
    fi
done
# Backup containers
if [ "$2" == 'full' ]; then
    for i in ${CONTAINERS[@]}
    do
        if [ "$RUN_OPTION" == 'restore' ]; then
            echo "Restoring docker-compose.yml containers"
            echo "This feature is not yet implemented..."
        else
            echo "Backing up docker-compose.yml containers"
            docker export $i > $i.tar
            restic backup $i.tar
            rm $i.tar
        fi
    done
fi
# If user is root, then copy over the .ssh details
if [[ $EUID -eq 0 ]]; then
    cp -rf /home/$ANSIBLE_PLAYBOOK_USER/.ssh/* /root/.ssh
fi
echo "Adding latest changes to the Git repository"
git add --all
git commit -m "Megabyte Labs Docker backup"
git push origin master
# Clean up files copied over when user is root
if [[ $EUID -eq 0 ]]; then
    rm -rf /root/.ssh/*
fi
echo "Bringing the project back online"
docker-compose up -d
if [ "$RUN_OPTION" == 'restore' ]; then
    if [ -f restore.sh ]; then
        echo "Running restore.sh"
        bash restore.sh
    fi
else
    if [ -f backup.sh ]; then
        echo "Running backup.sh"
        bash backup.sh
    fi
fi
