#!/usr/bin/env bash

# Streams an encrypted backup to an FTP server
# The backup replaces the previous one, but only after it is successfully sent
# See https://chanibal.pl/notes/encrypted-streaming-backup/ for up to date version

# Configuration start
export MCRYPT_ALGO="xtea"
export MCRYPT_MODE="ecb"
export MCRYPT_KEY="your-very-secret-password"
FTP_USER="your-ftp-user@your-ftp-host.tld"
FTP_PASS="your-ftp-password"
FTP_HOST="your-ftp-host"
FTP_FILE="your-backup-name.tar.bz2.mcrypt"
FTP_USE_TEMPORARY=false
# Configuration end

set -eo pipefail

if [[ "$MCRYPT_KEY" = "your-very-secret-password" ]]; then
  echo "Error: you should properly configure the script before using it."
  exit 2
fi

case "${1:-}" in
  "backup")
    if [[ ! $# -eq 1 ]]; then
      echo "Backup does not support positional params"
      exit 1
    fi

    USE_TEMPORARY_FLAG=""
    if [ "$FTP_USE_TEMPORARY" == true ]; then
      USE_TEMPORARY_FLAG="-S .tmp"
    fi

    echo "Backup started $(date -Is)"
    ncftpls -al -u "$FTP_USER" -p "$FTP_PASS" "ftp://${FTP_HOST}/${FTP_FILE}" \
      | awk '1 { printf ( "Previous backup size: %.3fGB\n", $5 / 1073741824 ) }'
    tar cjf - /etc /srv /home | mcrypt \
    | ncftpput -c $USE_TEMPORARY_FLAG -u "$FTP_USER" \
                -p "$FTP_PASS" "$FTP_HOST" "$FTP_FILE"
    ncftpls -al -u "$FTP_USER" -p "$FTP_PASS" "ftp://${FTP_HOST}/${FTP_FILE}" \
      | awk '1 { printf ( "New backup size: %.3fGB\n", $5 / 1073741824 ) }'
    echo "Backup ended $(date -Is)"
    ;;

  "restore")
    if [[ ! $# -eq 3 ]]; then
      echo "Restore requires two arguments"
      exit 1
    fi

    restore_file="$2"
    restore_destination="$3"
    
    mcrypt -d <"$restore_file" \
      | (mkdir -p "$restore_destination"; cd "$restore_destination"; tar xjf -)
    ;;

  "--help"|"-h"|"help"|*)
    echo "Streaming backup, usage:"
    echo "./backup-stream.sh backup"
    echo "./backup-stream.sh restore <restore_file> <restore_destination>"
    exit
    ;;
esac

