#!/bin/sh

BACKUP_DIR="/home/rohrnwo-it/backups"
DATE="2026-08-10"

SUCCESS_LOG="$BACKUP_DIR/success.log.txt"
ERROR_LOG="$BACKUP_DIR/error.log.txt"

SITES="
/home/rohrnwo-it/hanbud-ogrodzenia
/home/rohrnwo-it/ecoroof
/home/rohrnwo-it/hanbud_de
/home/rohrnwo-it/hanbud_lotwa
/home/rohrnwo-it/hanbud_ro
/home/rohrnwo-it/hanbudtvoros.lt
/home/rohrnwo-it/hanbud_lt
/home/rohrnwo-it/sztachety_de
"

mkdir -p "$BACKUP_DIR"

: > "$SUCCESS_LOG"
: > "$ERROR_LOG"

echo "Backup start: $(date)" >> "$SUCCESS_LOG"

for dir in $SITES
do
    name=$(basename "$dir")
    archive="$BACKUP_DIR/${DATE}_${name}_full.tar.gz"

    echo "Processing: $dir"

    if [ ! -d "$dir" ]; then
        echo "$(date) - ERROR - Directory not found: $dir" >> "$ERROR_LOG"
        continue
    fi

    if [ ! -f "$dir/wp-config.php" ]; then
        echo "$(date) - WARNING - wp-config.php not found: $dir" >> "$ERROR_LOG"
        continue
    fi

    if [ -f "$archive" ]; then
        echo "$(date) - INFO - Removing existing archive: $archive" >> "$SUCCESS_LOG"
        rm -f "$archive"

        if [ $? -ne 0 ]; then
            echo "$(date) - ERROR - Could not remove existing archive: $archive" >> "$ERROR_LOG"
            continue
        fi
    fi

    echo "$(date) - START - $name" >> "$SUCCESS_LOG"

    tar -czf "$archive" -C "$(dirname "$dir")" "$name"

    if [ $? -eq 0 ]; then
        size=$(du -h "$archive" | cut -f1)
        echo "$(date) - SUCCESS - $name - archive: $(basename "$archive") - size: $size" >> "$SUCCESS_LOG"
    else
        echo "$(date) - ERROR - Backup failed: $name" >> "$ERROR_LOG"
        rm -f "$archive"
        continue
    fi

    tar -tzf "$archive" > /dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo "$(date) - VERIFIED - $name - archive integrity OK" >> "$SUCCESS_LOG"
    else
        echo "$(date) - ERROR - Archive verification failed: $archive" >> "$ERROR_LOG"
    fi
done

echo "Backup finished: $(date)" >> "$SUCCESS_LOG"

exit 0
