#!/usr/bin/env bash
set -euo pipefail
source "$stpRoot/lib/log.sh"
source "$stpRoot/lib/utils.sh"

readonly thunderbirdApplicationDirectory="$HOME/snap/thunderbird/common"
readonly thunderbirdProfileDirectory="$thunderbirdApplicationDirectory/.thunderbird"
readonly thunderbirdArchive="$stpRoot/secrets/thunderbirdProfile.zip"

thunderbirdIsInstalled() {
    util::isSnapInstalled "thunderbird"
}

thunderbirdProfileExists() {
    [[ -f "$thunderbirdProfileDirectory/profiles.ini" ]]
}

installThunderbird() {
    sudo snap install thunderbird
    log::ok "Thunderbird instalado"
}

restoreProfile() {
    log::info "Restaurando perfil desde secrets/thunderbirdProfile.zip..."
    mkdir -p "$thunderbirdApplicationDirectory"
    unzip -qo "$thunderbirdArchive" -d "$thunderbirdApplicationDirectory"
    log::ok "Perfil restaurado en: $thunderbirdProfileDirectory"
}

if thunderbirdIsInstalled; then
    log::info "Thunderbird ya instalado"
else
    installThunderbird
fi

if [[ ! -f "$thunderbirdArchive" ]]; then
    log::info "Sin respaldo de perfil (secrets/thunderbirdProfile.zip), salteando restauración"
    exit 0
fi

if thunderbirdProfileExists; then
    log::info "Perfil de Thunderbird ya existe, salteando restauración"
    exit 0
fi

restoreProfile
