#!/usr/bin/with-contenv bashio
set -e

# --- Fonction de synchronisation Git ---
sync_git() {
    bashio::log.info "=== Service de synchronisation Git 2 ==="
    local REPO=$(bashio::config 'git_repository')
    bashio::log.info "=== Service de synchronisation Git 3 ==="
    local BRANCH=$(bashio::config 'git_branch')
    bashio::log.info "=== Service de synchronisation Git 4 ==="
    local USERNAME=$(bashio::config 'git_username')
    bashio::log.info "=== Service de synchronisation Git 5 ==="
    local PASSWORD=$(bashio::config 'git_password')
    bashio::log.info "=== Service de synchronisation Git 6 ==="
    local PATH=$(bashio::config 'recipes_path')
    bashio::log.info "=== Service de synchronisation Git 7 ==="

    if [ -z "$REPO" ]; then
        bashio::log.info "Aucun dépôt Git configuré. Attente..."
        sleep infinity
        return
    fi

    bashio::log.info "Synchronisation avec ${REPO} (branche: ${BRANCH})"

    # Construction de l'URL avec authentification si nécessaire
    local AUTH_URL="$REPO"
    if [ -n "$USERNAME" ] && [ -n "$PASSWORD" ]; then
        # Supposons que l'URL est de type https://github.com/user/repo.git
        local PROTOCOL="https://"
        local REPO_WITHOUT_PROTOCOL="${REPO#https://}"
        REPO_WITHOUT_PROTOCOL="${REPO_WITHOUT_PROTOCOL#http://}"
        AUTH_URL="${PROTOCOL}${USERNAME}:${PASSWORD}@${REPO_WITHOUT_PROTOCOL}"
        bashio::log.info "Authentification configurée pour ${USERNAME}"
    fi

    # Clone ou pull
    if [ ! -d "$PATH/.git" ]; then
        bashio::log.info "Premier clone du dépôt..."
        git clone --branch "$BRANCH" "$AUTH_URL" "$PATH" 2>&1 | bashio::log.info
    else
        bashio::log.info "Mise à jour du dépôt existant..."
        cd "$PATH"
        # Réinitialisation pour éviter les conflits
        git fetch origin "$BRANCH" 2>&1 | bashio::log.info
        git reset --hard "origin/$BRANCH" 2>&1 | bashio::log.info
        cd - > /dev/null
    fi

    bashio::log.info "Synchronisation Git terminée."
}

# --- Fonction de synchronisation périodique ---
periodic_sync() {
    local INTERVAL=$(bashio::config 'git_sync_interval')
    if [ -z "$INTERVAL" ] || [ "$INTERVAL" -eq 0 ]; then
        INTERVAL=3600
    fi
    
    bashio::log.info "Synchronisation périodique configurée toutes les ${INTERVAL}s"
    
    while true; do
        sleep "$INTERVAL"
        bashio::log.info "=== Synchronisation Git périodique ==="
        sync_git
    done
}

# --- Exécution ---
bashio::log.info "=== Service de synchronisation Git ==="

# Premier sync au démarrage
sync_git

# Lancement du sync périodique en arrière-plan
periodic_sync &