#!/bin/bash

source /usr/share/yunohost/helpers

ynh_abort_if_errors

borg="$install_dir/venv/bin/borg"

#=================================================
# SPECIFIC GETTERS FOR TOML SHORT KEY
#=================================================

get__info() {
        cat << EOF
ask:
  en: "**Backup state**: ${old[state]}

    **Last run**: ${old[last_run]}"
EOF
    if [ "${old[state]}" == "failed" ]; then
        cat << EOF
style: "danger"
EOF
    elif [ "${old[state]}" == "successful" ]; then
        cat << EOF
style: "success"
EOF
    else
        cat << EOF
style: "info"
EOF
    fi
}

get__ssh_public_key() {
    cat << EOF
ask:
  en: "**Public key**: \`$(cat /root/.ssh/id_${app}_ed25519.pub || echo '')\`"
EOF
}

get__data_multimedia() {
    if [ -e /home/yunohost.multimedia/.nobackup ]; then
        echo "value: false"
    else
        echo "value: true"
    fi
}
get__last_backups() {
    cat << EOF
ask: |-
$(BORG_PASSPHRASE="$(ynh_app_setting_get $app passphrase)" BORG_RSH="ssh -i /root/.ssh/id_${app}_ed25519 -oStrictHostKeyChecking=yes " "$borg" list --short --last 50 ${old[repository]} | sed 's/^/  /g' 2> /dev/null)
EOF
}

get__conf() {
    ynh_app_setting_get --app=$app --key=conf
}

#=================================================
# SPECIFIC VALIDATORS FOR TOML SHORT KEYS
#=================================================
validate__on_calendar() {

    (systemd-analyze calendar $on_calendar > /dev/null) ||
        echo 'Please follow systemd OnCalendar format: https://man.archlinux.org/man/systemd.time.7#CALENDAR_EVENTS'
}

#=================================================
# SPECIFIC SETTERS FOR TOML SHORT KEYS
#=================================================

set__data_multimedia() {
    if [ "$data_multimedia" == "0" ]; then
        mkdir -p /home/yunohost.multimedia/
        touch /home/yunohost.multimedia/.nobackup
    else
        ynh_secure_remove /home/yunohost.multimedia/.nobackup
    fi
}

set__conf() {
    if [ -n "${conf}" ]
    then
        # Update the config of the app
        ynh_app_setting_set --app=$app --key=conf --value=$conf
    fi
}

#=================================================
# GENERIC FINALIZATION
#=================================================
ynh_app_config_run $1
