#!/usr/bin/env bash

toBackupDir='/home/pi'
backupsDir='/media/pimain/backup-tmp/pi'

# Space-separated directory names to ignore (directories will be pruned)
# Example: ignoreDirNames=".venv target node_modules build"
# Leave empty to include all directories.
ignoreDirNames="immich homeassistant test .ssh .venv target node_modules build .config .cache .cargo .docker foty .m2 .npm .oh-my-zsh .ollama .local .giti tmp temp testowe"

# Space-separated file name patterns to ignore (globs). Example:
# ignoreFilePatterns="*.jpg *.png *.jar"
# Leave empty to include all file patterns.
#ignoreFilePatterns="*.jpg *.jped *.png *.jar *.mp4 *mp3"
ignoreFilePatterns=""

# Get current date in YYYYMMDD format
dateStamp=$(date +%Y%m%d)
backupFolderPrefix="pihome_"

# Function to check if backup is from last day of month
is_last_day_of_month() {
    local file=$1
    local date=$(basename "$file" .tgz)
    # Check if next day is first day of next month
    if [ "$(date -d "$date +1 day" +%d)" = "01" ]; then
        return 0
    else
        return 1
    fi
}

# Create tar.gz archive file list with optional ignored directories
if cd "$toBackupDir"; then
    # Build prune expression for find from ignoreDirNames
    prune_expr=()
    if [ -n "$ignoreDirNames" ]; then
        for d in $ignoreDirNames; do
            prune_expr+=( -name "$d" -o )
        done
        # remove trailing -o
        unset 'prune_expr[${#prune_expr[@]}-1]'
    else
        # ensure valid find expression when nothing to prune
        prune_expr=( -false )
    fi

    # Build file-name ignore expression from ignoreFilePatterns
    name_expr=()
    if [ -n "$ignoreFilePatterns" ]; then
        for p in $ignoreFilePatterns; do
            name_expr+=( -name "$p" -o )
        done
        # remove trailing -o
        unset 'name_expr[${#name_expr[@]}-1]'
    else
        # ensure valid find expression when nothing to exclude by name
        name_expr=( -false )
    fi

    if find . \( -type d \( "${prune_expr[@]}" \) -prune \) -o \( -type f ! \( "${name_expr[@]}" \) -print0 \) | tar -czf "$backupsDir/$backupFolderName${dateStamp}.tgz" --null -T -; then
        chown pi:pi $backupsDir/$backupFolderName${dateStamp}.tgz

        echo "Backup completed successfully: $backupsDir/$backupFolderName${dateStamp}.tgz"

        # Remove backups older than 7 days except last day of month backups
        find "$backupsDir" -name "${backupFolderPrefix}*.tgz" -type f -mtime +7 | while read -r file; do
            fileDtgName=$(echo $file | cut -d '_' -f 2)
            if ! is_last_day_of_month "$fileDtgName"; then
                rm "$fileDtgName"
            fi
        done

    else
        echo "Error creating backup"
        exit 1
    fi
else
    echo "Error: cannot cd to $toBackupDir"
    exit 1
fi
