#!/bin/bash

# Script di sincronizzazione bidirezionale
# Uso: ./sync-bidirectional.sh [push|pull]

MODE=${1:-push}
LOCAL_PATH="$HOME/netgescon/netgescon-laravel/"
REMOTE_USER="michele"
REMOTE_HOST="192.168.0.43"
REMOTE_PATH="/var/www/netgescon/"

case $MODE in
    push)
        echo "🔄 PUSH: Sincronizzazione locale -> remoto..."
        if [ -f .rsyncignore ]; then
            rsync -rz --delete --checksum --exclude-from=.rsyncignore \
              $LOCAL_PATH $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH
        else
            rsync -rz --delete --checksum --exclude='.git' --exclude='node_modules' --exclude='vendor' --exclude='storage/logs' --exclude='storage/framework' --exclude='bootstrap/cache' \
              $LOCAL_PATH $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH
        fi
        
        if [ $? -eq 0 ]; then
            echo "✅ Push completato!"
            echo "🔧 Aggiornamento remoto..."
            ssh $REMOTE_USER@$REMOTE_HOST "cd $REMOTE_PATH && php artisan migrate --force"
        fi
        ;;
    pull)
        echo "🔄 PULL: Sincronizzazione remoto -> locale..."
        if [ -f .rsyncignore ]; then
            rsync -rz --delete --checksum --exclude-from=.rsyncignore \
              $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH $LOCAL_PATH
        else
            rsync -rz --delete --checksum --exclude='.git' --exclude='node_modules' --exclude='vendor' --exclude='storage/logs' --exclude='storage/framework' --exclude='bootstrap/cache' \
              $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH $LOCAL_PATH
        fi
        
        if [ $? -eq 0 ]; then
            echo "✅ Pull completato!"
            echo "🔧 Aggiornamento locale..."
            cd $LOCAL_PATH
            composer install
            php artisan migrate
        fi
        ;;
    *)
        echo "Uso: $0 [push|pull]"
        echo "  push: Sincronizza locale -> remoto (default)"
        echo "  pull: Sincronizza remoto -> locale"
        exit 1
        ;;
esac
