#!/bin/bash

gitCheckForUpdate()
{

    # Check the status of the local repository
    cd "$script_dir"
    
    # If Git login is required, get credentials first
    if [[ $CFG_INSTALL_MODE == "git" ]]; then
        while true; do
            gitCheckGitDetails;            
            # Test the credentials by trying to fetch
            if runAsManager git -c "credential.helper=" -c "credential.helper=!f() { echo username=$CFG_GIT_USER; echo password=$CFG_GIT_KEY; }; f" fetch > /dev/null 2>&1; then
                isSuccessful "Git authentication successful"
                break
            else
                runReinstall;
            fi
        done
    fi
    
    # Proceed with the fetch using the credentials if they were provided
    if [[ $CFG_INSTALL_MODE == "git" ]]; then
        runAsManager git -c "credential.helper=" -c "credential.helper=!f() { echo username=$CFG_GIT_USER; echo password=$CFG_GIT_KEY; }; f" fetch > /dev/null 2>&1
    else
        runAsManager git fetch > /dev/null 2>&1
    fi
    if runAsManager git status | grep -q "Your branch is ahead"; then
        isSuccessful "The repository is up to date...continuing..."
    elif runAsManager git status | grep -q "Your branch is up to date with"; then
        isSuccessful "The repository is up to date...continuing..."
    else
        isNotice "Updates found."
        if [[ $CFG_GIT_AUTO_UPDATES == "true" ]]; then
            gitFolderResetAndBackup;
        else
            while true; do
                isQuestion "Do you want to update LibrePortal now? (y/n): "
                read -rp "" acceptupdates
                if [[ "$acceptupdates" =~ ^[yYnN]$ ]]; then
                    break
                fi
                isNotice "Please provide a valid input (y/n)."
            done
            if [[ $acceptupdates == [yY] ]]; then
                gitFolderResetAndBackup;
            fi
        fi
    fi
}
