#!/usr/bin/env bash
set -Eeuo pipefail

borg="__INSTALL_DIR__/venv/bin/borg"
app="__APP__"

BORG_PASSPHRASE="$(yunohost app setting "$app" passphrase)"
BORG_REPO="$(yunohost app setting "$app" repository)"
BORG_LOGGING_CONF="__INSTALL_DIR__/logging.conf"

if ssh-keygen -F "__SERVER__" >/dev/null ; then
    BORG_RSH="ssh -i /root/.ssh/id_${app}_ed25519 -oStrictHostKeyChecking=yes "
else
    BORG_RSH="ssh -i /root/.ssh/id_${app}_ed25519 -oStrictHostKeyChecking=no "
fi

do_need_mount() {
    true
}

do_backup() {
    export BORG_PASSPHRASE
    export BORG_REPO
    export BORG_RSH
    export BORG_LOGGING_CONF
    export BORG_RELOCATED_REPO_ACCESS_IS_OK=yes
    work_dir="$1"
    name="$2"
    size="$3"
    description="$4"
    set +e
    if ! "$borg" list > /dev/null 2>&1; then
        "$borg" init -e repokey
        # human_size=`echo $size | awk '{ suffix=" KMGT"; for(i=1; $1>1024 && i < length(suffix); i++) $1/=1024; print int($1) substr(suffix, i, 1), $3; }'`
        # Speed in Kbps
        # speed=1000
        # evaluated_time=$(($size / ($speed * 1000 / 8) / 3600))
        echo "Hello,

Your first backup on $BORG_REPO is starting.

This is an automated message from your beloved YunoHost server." | /usr/bin/mail.mailutils -a "Content-Type: text/plain; charset=UTF-8" -s "[YNH] First backup is starting" "root"
    fi
    set -e

    # About the {now} placeholder:
    # https://borgbackup.readthedocs.io/en/stable/usage/create.html#description
    # In the archive name, you may use the following placeholders: {now}, {utcnow}, {fqdn}, {hostname}, {user} and some others.
    "$borg" create --stats "::${name}-{now}" "$work_dir"

    "$borg" prune --glob-archives "${name}-*" --list --keep-hourly 2 --keep-daily=7 --keep-weekly=8 --keep-monthly=12

    # We prune potential manual backup older than 1 year
    "$borg" prune --list --keep-within 1y
}

do_mount() {
    export BORG_PASSPHRASE
    export BORG_REPO
    export BORG_RSH
    export BORG_LOGGING_CONF
    work_dir="$1"
    name="$2"
    size="$3"
    description="$4"
    "$borg" mount "::$name" "$work_dir"
}

work_dir="$2"
name="$3"

size="$5"
description="$6"

case "$1" in
  need_mount)
    do_need_mount "$work_dir" "$name" "$size" "$description"
    ;;
  backup)
    do_backup "$work_dir" "$name" "$size" "$description"
    ;;
  mount)
    do_mount "$work_dir" "$name" "$size" "$description"
    ;;
  *)
    echo "hook called with unknown argument \`$1'" >&2
    exit 1
    ;;
esac

exit 0
