#!/usr/bin/env bash

wineqgui-restore()
{
    local backupdir
    local prefixdir
    local selection
    local metadata
    local archive
    local name
    local prefix
    local backup_date
    local restore_parent
    local entries=()

    backupdir="${HOME}/.local/share/wineqgui/backups"
    prefixdir="${HOME}/.local/share/wineqgui/prefixes"

    mkdir -p "$backupdir"
    mkdir -p "$prefixdir"


    # -------------------------------------------------
    # Finn backup-metadata
    # -------------------------------------------------

    while IFS= read -r -d '' metadata; do

        name=$(read_config_value "$metadata" "NAME")
        backup_date=$(read_config_value "$metadata" "DATE")

        [[ -z "$name" ]] && continue

        entries+=("${name} — ${backup_date}" "$metadata")

    done < <(
        find "$backupdir" \
            -type f \
            -name '*.meta' \
            -print0
    )


    # -------------------------------------------------
    # Ingen backups
    # -------------------------------------------------

    if (( ${#entries[@]} == 0 )); then
        show_info "There are no WineQGUI backups to restore."
        return
    fi


    # -------------------------------------------------
    # Vel backup
    # -------------------------------------------------

    selection=$(
        qarma --list \
            --title="Restore Wine application" \
            --width=680 \
            --height=420 \
            --hide-header \
            --column="Backup" \
            --column="Metadata" \
            "${entries[@]}"
    )

    [[ -z "$selection" ]] && return


    metadata="$selection"

    name=$(read_config_value "$metadata" "NAME")
    prefix=$(read_config_value "$metadata" "PREFIX")
    archive=$(read_config_value "$metadata" "ARCHIVE")
    backup_date=$(read_config_value "$metadata" "DATE")


    # -------------------------------------------------
    # Kontroller backup
    # -------------------------------------------------

    if [[ ! -f "$archive" ]]; then
        show_error \
            "Backup archive does not exist:\n\n<b>${archive}</b>"
        return 1
    fi


    # Berre restore til WineQGUI-eigde miljø
    case "$prefix" in
        "${prefixdir}"/*)
            ;;
        *)
            show_error \
                "WineQGUI will not restore this backup because its target environment is outside WineQGUI's managed directory."
            return 1
            ;;
    esac


    # -------------------------------------------------
    # Stadfest
    # -------------------------------------------------

    if [[ -d "$prefix" ]]; then

        if ! qarma --question \
            --title="Restore ${name}" \
            --text="<b>Warning</b>\n\n"\
            "The current Wine environment already exists.\n\n"\
            "Restoring this backup will replace it completely.\n\n"\
            "<b>${name}</b>\n"\
            "Backup: ${backup_date}\n\n"\
            "Continue?"
        then
            return
        fi

    else

        if ! qarma --question \
            --title="Restore ${name}" \
            --text="Restore backup for:\n\n<b>${name}</b>\n\nBackup: ${backup_date}?"
        then
            return
        fi

    fi


    # -------------------------------------------------
    # Restore
    # -------------------------------------------------

    restore_parent="$(dirname "$prefix")"

    (
        echo "10"
        echo "# Preparing restore..."

        sleep 0.3

        if [[ -d "$prefix" ]]; then
            echo "30"
            echo "# Removing current Wine environment..."

            rm -rf -- "$prefix"
        fi

        echo "50"
        echo "# Restoring Wine environment..."

        mkdir -p "$restore_parent"

        if tar -xzf "$archive" \
            -C "$restore_parent"
        then
            echo "100"
            echo "# Restore completed."
        else
            exit 1
        fi

    ) |
    qarma --progress \
        --title="Restoring ${name}" \
        --text="Restoring backup..." \
        --percentage=0 \
        --auto-close

    status=${PIPESTATUS[0]}

    if [[ "$status" -ne 0 ]]; then
        show_error \
            "Restore failed for:\n\n<b>${name}</b>"
        return 1
    fi


    if [[ ! -d "$prefix" ]]; then
        show_error \
            "The archive was extracted, but the expected Wine environment was not found."
        return 1
    fi


    show_info \
        "Backup restored successfully:\n\n<b>${name}</b>\n\n${backup_date}"
}
