#!/bin/bash

# gitPerformUpdate — the proven, file-level LibrePortal update.
#
# Backs up the user's configs/logs, re-clones the repo fresh (gitReset), then
# restores the configs/logs over the clean checkout, zips a snapshot, prunes
# old backups, and stops tracking ignored files. This is the historical update
# body that "worked great" — extracted out of gitFolderResetAndBackup so it can
# be reused non-interactively by the WebUI updater (webuiRunUpdate) WITHOUT the
# trailing `exit` the interactive CLI flow relies on.
#
# Does NOT exit, restart, or redeploy — the caller decides what happens next.
gitPerformUpdate()
{
    isHeader "Updating LibrePortal"
    update_done=false

    if [ ! -d "$backup_install_dir/$backupFolder" ]; then
        local result=$(createFolders "loud" $sudo_user_name "$backup_install_dir/$backupFolder")
        checkSuccess "Create the backup folder"
    fi
    local result=$(cd $backup_install_dir)
    checkSuccess "Going into the backup install folder"

    local result=$(copyFolder "$configs_dir" "$backup_install_dir/$backupFolder" "$sudo_user_name")
    checkSuccess "Copy the configs to the backup folder"
    local result=$(copyFolder "$logs_dir" "$backup_install_dir/$backupFolder" "$sudo_user_name")
    checkSuccess "Copy the logs to the backup folder"

    gitReset;

    local result=$(copyFolders "$backup_install_dir/$backupFolder/" "$docker_dir" "$sudo_user_name")
    checkSuccess "Copy the backed up folders back into the installation directory"

    local result=$(runAsManager zip -r "$backup_install_dir/$backupFolder.zip" "$backup_install_dir/$backupFolder")
    checkSuccess "Zipping up the the backup folder for safe keeping"

    gitCleanInstallBackups;

    gitUntrackFiles;
}

gitFolderResetAndBackup()
{
    gitPerformUpdate;

    isSuccessful "Custom changes have been discarded successfully"
    echo ""
    isNotice "You have updated your version of LibrePortal."
    isNotice "To avoid any issues please rerun the 'libreportal'."
    echo ""
    exit
    update_done=true
}
