#!/bin/bash
#
# Mirror Fedora 45
#

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH
export LC_ALL=C

RELEASE="45"

DEST_BASE="/data/fedora/linux"
LOCKFILE="${DEST_BASE}/.mirror-fedora-${RELEASE}.lock"

#
# Leave empty for unlimited bandwidth.
#
# Example:
#
# BWLIMIT="50000"
#
BWLIMIT="${BWLIMIT:-}"

#
# Maximum percentage of existing files in the updates repository
# that rsync is allowed to delete during one synchronization.
#
# Default: 20 percent
#
# Override when running, for example:
#
# MAX_DELETE_PERCENT=10 /usr/local/bin/mirror-fedora-44.sh
#
# Set to 0 to disable the deletion limit completely.
#
MAX_DELETE_PERCENT="${MAX_DELETE_PERCENT:-20}"

#
# Rsync progress display.
#
# Available modes:
#
#   progress  = traditional rsync --progress (default)
#   progress2 = overall progress using --info=progress2,stats2
#   stats     = statistics only
#   none      = no additional progress/statistics output
#
# Examples:
#
# RSYNC_PROGRESS=progress2 /usr/local/bin/mirror-fedora-44.sh
# RSYNC_PROGRESS=stats     /usr/local/bin/mirror-fedora-44.sh
# RSYNC_PROGRESS=none      /usr/local/bin/mirror-fedora-44.sh
#
RSYNC_PROGRESS="${RSYNC_PROGRESS:-progress}"

#
# Mirrors in preferred order.
#
MIRRORS=(
    "rsync://mirror.accum.se/mirror/fedora/linux"
    "rsync://mirror.netone.nl/fedora-linux/linux"
    "rsync://ftp-stud.hs-esslingen.de/fedora/linux"
)

#
# Files/directories not mirrored.
#
EXCLUDES=(
    "--exclude=debug"
    "--exclude=drpms"
    "--exclude=*.torrent"
    "--exclude=.rsync-partial/"
)

#
# Common rsync options.
#
RSYNC_OPTS=(
    -a
    --no-motd
    --partial
    --partial-dir=.rsync-partial
    --contimeout=30
    --timeout=300
)

if [ -n "$BWLIMIT" ]; then
    RSYNC_OPTS+=( "--bwlimit=${BWLIMIT}" )
fi


#
# Select progress/statistics mode.
#
case "$RSYNC_PROGRESS" in

    progress)
        RSYNC_OPTS+=( "--progress" )
        ;;

    progress2)
        RSYNC_OPTS+=( "--info=progress2,stats2" )
        ;;

    stats)
        RSYNC_OPTS+=( "--info=stats2" )
        ;;

    none)
        ;;

    *)
        echo "ERROR: Invalid RSYNC_PROGRESS value: $RSYNC_PROGRESS"
        echo "Valid values are: progress, progress2, stats, none"
        exit 1
        ;;

esac


#
# Logging.
#
log()
{
    echo "$(date '+%Y-%m-%d %H:%M:%S') $*"
}


#
# Refuse to run as root.
#
if [ "$(id -u)" = "0" ]; then
    echo "ERROR: Refuses to run as the root user. Correct usage is:"
    echo "su - syncer -c \"$0\""
    exit 1
fi


#
# Validate MAX_DELETE_PERCENT.
#
if ! echo "$MAX_DELETE_PERCENT" | grep -Eq '^[0-9]+$'; then
    echo "ERROR: MAX_DELETE_PERCENT must be an integer."
    exit 1
fi

if [ "$MAX_DELETE_PERCENT" -gt 100 ]; then
    echo "ERROR: MAX_DELETE_PERCENT cannot be greater than 100."
    exit 1
fi


#
# Make sure base directory exists.
#
mkdir -p "$DEST_BASE"

if [ "$?" -ne 0 ]; then
    echo "ERROR: Could not create $DEST_BASE"
    exit 1
fi


#
# Prevent multiple simultaneous instances.
#
# The existence of LOCKFILE itself does NOT mean that the repository
# is locked. flock() determines whether an active kernel lock exists.
#
# An old lock file from a terminated process is harmless and will be
# reused if no active kernel lock exists.
#
# The lock file contains information about the process that acquired
# the lock, which makes troubleshooting easier.
#

if [ ! -e "$LOCKFILE" ]; then
    : > "$LOCKFILE"

    if [ "$?" -ne 0 ]; then
        log "ERROR: Could not create lock file:"
        log "       ${LOCKFILE}"
        exit 1
    fi
fi


#
# Open without truncating the existing lock file.
#
exec 9<>"$LOCKFILE"

if [ "$?" -ne 0 ]; then
    log "ERROR: Could not open lock file:"
    log "       ${LOCKFILE}"
    exit 1
fi


#
# Try to acquire the kernel lock.
#
flock -n 9
LOCK_RC="$?"


if [ "$LOCK_RC" -ne 0 ]; then

    log "Another mirror-fedora-${RELEASE} process still holds the lock."
    log "Lock file:"
    log "    ${LOCKFILE}"

    LOCK_PID=$(
        awk -F= '$1 == "PID" {print $2; exit}' \
            "$LOCKFILE" 2>/dev/null
    )

    LOCK_STARTED=$(
        awk -F= '$1 == "STARTED" {
            sub(/^STARTED=/, "")
            print
            exit
        }' "$LOCKFILE" 2>/dev/null
    )

    LOCK_SCRIPT=$(
        awk -F= '$1 == "SCRIPT" {
            sub(/^SCRIPT=/, "")
            print
            exit
        }' "$LOCKFILE" 2>/dev/null
    )


    if [ -n "$LOCK_PID" ]; then

        log "Recorded lock owner:"
        log "    PID     : ${LOCK_PID}"

        if [ -n "$LOCK_STARTED" ]; then
            log "    Started : ${LOCK_STARTED}"
        fi

        if [ -n "$LOCK_SCRIPT" ]; then
            log "    Script  : ${LOCK_SCRIPT}"
        fi


        kill -0 "$LOCK_PID" 2>/dev/null

        if [ "$?" -eq 0 ]; then

            log "Recorded PID ${LOCK_PID} is still running."

            ps -p "$LOCK_PID" \
                -o pid,ppid,user,lstart,cmd \
                --no-headers 2>/dev/null |
            sed 's/^/    /'

        else

            log "Recorded PID ${LOCK_PID} is no longer running."
            log "The lock may be held by a surviving child process."

        fi

    else

        log "No process information was stored in the lock file."

    fi


    #
    # Try to show the real kernel lock holder.
    #
    if command -v lslocks >/dev/null 2>&1; then

        LOCK_HOLDER=$(
            lslocks -n -o PID,COMMAND,PATH 2>/dev/null |
            awk -v lock="$LOCKFILE" '$3 == lock'
        )

        if [ -n "$LOCK_HOLDER" ]; then

            log "Kernel lock information:"
            echo "$LOCK_HOLDER" |
            sed 's/^/    /'

        fi

    fi


    exit 1
fi


#
# We acquired the lock.
#
# Any old information in the file is now stale and may safely
# be replaced with information about this run.
#
: > "$LOCKFILE"

printf 'PID=%s\n' "$$" >&9
printf 'STARTED=%s\n' "$(date '+%Y-%m-%d %H:%M:%S')" >&9
printf 'SCRIPT=%s\n' "$0" >&9

log "Lock acquired."
log "    PID       : $$"
log "    Lock file : ${LOCKFILE}"


#
# Basic sanity check of an upstream Fedora repository.
#
# This protects against mirrors that answer rsync requests but have
# an incomplete or nearly empty Fedora tree.
#
repo_sane()
{
    local src="${1%/}"
    local listing
    local rc
    local size
    local package_listing
    local package_dirs


    #
    # Check repodata/repomd.xml.
    #
    # --no-h prevents rsync from adding digit separators to the size.
    #
    # FD 9 is explicitly closed in rsync child processes so that an
    # interrupted parent shell cannot leave the lock held by rsync.
    #
    listing=$(
        rsync \
            --no-motd \
            --no-h \
            --contimeout=20 \
            --timeout=60 \
            --list-only \
            "${src}/repodata/repomd.xml" \
            9>&- 2>/dev/null
    )

    rc="$?"

    if [ "$rc" -ne 0 ]; then
        log "Sanity check failed:"
        log "    repodata/repomd.xml unavailable"
        log "    rsync exit code: ${rc}"
        return 1
    fi


    size=$(
        echo "$listing" |
        awk '$1 ~ /^-/ {print $2; exit}'
    )


    if ! echo "$size" | grep -Eq '^[0-9]+$'; then
        log "Sanity check failed:"
        log "    Could not parse repomd.xml size."
        log "    rsync returned:"
        log "    ${listing}"
        return 1
    fi


    #
    # Intentionally low threshold.
    # We only want to catch obviously broken metadata.
    #
    if [ "$size" -lt 1000 ]; then
        log "Sanity check failed:"
        log "    repomd.xml is suspiciously small."
        log "    Size: ${size} bytes"
        return 1
    fi


    #
    # Check that Packages/ exists and contains several directories.
    #
    package_listing=$(
        rsync \
            --no-motd \
            --no-h \
            --contimeout=20 \
            --timeout=60 \
            --list-only \
            "${src}/Packages/" \
            9>&- 2>/dev/null
    )

    rc="$?"

    if [ "$rc" -ne 0 ]; then
        log "Sanity check failed:"
        log "    Packages/ unavailable"
        log "    rsync exit code: ${rc}"
        return 1
    fi


    package_dirs=$(
        echo "$package_listing" |
        awk '$1 ~ /^d/ {n++} END {print n+0}'
    )


    if ! echo "$package_dirs" | grep -Eq '^[0-9]+$'; then
        log "Sanity check failed:"
        log "    Could not count Packages/ directories."
        return 1
    fi


    if [ "$package_dirs" -lt 5 ]; then
        log "Sanity check failed:"
        log "    Packages/ contains only ${package_dirs} directories."
        return 1
    fi


    log "Sanity check passed:"
    log "    repomd.xml size      : ${size} bytes"
    log "    Packages directories : ${package_dirs}"

    return 0
}


#
# Check how much of the local repository rsync intends to delete.
#
# This function performs a complete rsync dry-run using the same
# exclusions and --delete-delay that will be used during the real
# synchronization.
#
# Only files are counted. Directory deletions do not affect the
# percentage.
#
delete_sane()
{
    local src="${1%/}"
    local dest="${2%/}"

    local tmpfile
    local rc
    local local_files
    local delete_files
    local delete_percent


    #
    # A value of zero disables deletion protection.
    #
    if [ "$MAX_DELETE_PERCENT" -eq 0 ]; then
        log "Deletion safety limit disabled."
        return 0
    fi


    #
    # Count existing local files.
    #
    local_files=$(
        find "$dest" \
            -mindepth 1 \
            ! -type d \
            ! -path "${dest}/.rsync-partial/*" \
            -print 2>/dev/null |
        wc -l
    )

    local_files=$(echo "$local_files" | tr -d '[:space:]')


    if ! echo "$local_files" | grep -Eq '^[0-9]+$'; then
        log "WARNING: Could not determine number of local files."
        return 1
    fi


    #
    # Empty/new repository: nothing can be deleted.
    #
    if [ "$local_files" -eq 0 ]; then
        log "Deletion safety check:"
        log "    Local repository contains no files."
        log "    Nothing can be deleted."
        return 0
    fi


    log "Performing deletion safety dry-run."


    #
    # Store dry-run output in a temporary file.
    #
    # This preserves rsync's real return value without requiring
    # set -o pipefail.
    #
    tmpfile=$(mktemp "/tmp/mirror-fedora-${RELEASE}.XXXXXX")

    if [ "$?" -ne 0 ] || [ -z "$tmpfile" ]; then
        log "WARNING: Could not create temporary file for dry-run."
        return 1
    fi


    rsync \
        -a \
        --dry-run \
        --itemize-changes \
        --delete-delay \
        --no-motd \
        --contimeout=30 \
        --timeout=300 \
        "${EXCLUDES[@]}" \
        "${src}/" \
        "${dest}/" \
        >"$tmpfile" 2>&1 \
        9>&-

    rc="$?"


    if [ "$rc" -ne 0 ]; then

        log "WARNING: Deletion safety dry-run failed."
        log "    rsync exit code: ${rc}"

        if [ -s "$tmpfile" ]; then
            log "    rsync output:"
            sed 's/^/        /' "$tmpfile"
        fi

        rm -f "$tmpfile"

        return 1
    fi


    #
    # rsync deletion output looks like:
    #
    #     *deleting   Packages/a/example.rpm
    #
    # Directory deletions end in "/" and are ignored.
    #
    delete_files=$(
        awk '
            $1 == "*deleting" && $0 !~ /\/$/ {
                n++
            }
            END {
                print n+0
            }
        ' "$tmpfile"
    )

    rm -f "$tmpfile"


    if ! echo "$delete_files" | grep -Eq '^[0-9]+$'; then
        log "WARNING: Could not determine number of proposed deletions."
        return 1
    fi


    if [ "$delete_files" -eq 0 ]; then

        log "Deletion safety check:"
        log "    Local files         : ${local_files}"
        log "    Proposed deletions  : 0"
        log "    Deletion percentage : 0%"
        log "    Maximum allowed     : ${MAX_DELETE_PERCENT}%"
        log "Deletion safety check passed."

        return 0
    fi


    #
    # Calculate percentage rounded upwards.
    #
    delete_percent=$(
        echo $(( (delete_files * 100 + local_files - 1) / local_files ))
    )


    log "Deletion safety check:"
    log "    Local files         : ${local_files}"
    log "    Proposed deletions  : ${delete_files}"
    log "    Deletion percentage : ${delete_percent}%"
    log "    Maximum allowed     : ${MAX_DELETE_PERCENT}%"


    if [ "$delete_percent" -gt "$MAX_DELETE_PERCENT" ]; then
        log "WARNING: Deletion limit exceeded."
        log "WARNING: Refusing to synchronize from this mirror."
        return 1
    fi


    log "Deletion safety check passed."

    return 0
}


#
# Synchronize one Fedora repository.
#
# Arguments:
#
#   $1 = relative repository path
#   $2 = local destination
#   $3 = yes/no - allow deletion of local files
#
sync_repo()
{
    local relpath="$1"
    local dest="$2"
    local allow_delete="$3"

    local mirror
    local src
    local rc

    local DELETE_OPTS=()


    if [ "$allow_delete" = "yes" ]; then
        DELETE_OPTS+=( "--delete-delay" )
    fi


    mkdir -p "$dest"

    if [ "$?" -ne 0 ]; then
        log "ERROR: Could not create destination:"
        log "       ${dest}"
        return 1
    fi


    for mirror in "${MIRRORS[@]}"; do

        src="${mirror}/${relpath}/"


        log "------------------------------------------------------------"
        log "Checking:"
        log "    ${src}"


        #
        # Step 1:
        # Check the upstream repository.
        #
        repo_sane "$src"

        if [ "$?" -ne 0 ]; then
            log "WARNING: Repository rejected:"
            log "         ${src}"
            log "Trying next mirror."
            continue
        fi


        #
        # Step 2:
        # If deletion is enabled, perform the deletion safety test.
        #
        if [ "$allow_delete" = "yes" ]; then

            delete_sane "$src" "$dest"

            if [ "$?" -ne 0 ]; then
                log "WARNING: Deletion safety check failed for:"
                log "         ${src}"
                log "Trying next mirror."
                continue
            fi

        fi


        #
        # Step 3:
        # Perform the real synchronization.
        #
        log "Synchronizing from:"
        log "    ${src}"
        log "to:"
        log "    ${dest}"


        #
        # FD 9 is closed in the rsync child.
        #
        # This prevents a surviving rsync process from retaining the
        # flock lock if the parent shell is terminated.
        #
        rsync \
            "${RSYNC_OPTS[@]}" \
            "${EXCLUDES[@]}" \
            "${DELETE_OPTS[@]}" \
            "$src" \
            "${dest%/}/" \
            9>&-

        rc="$?"


        if [ "$rc" -eq 0 ]; then
            log "Successfully synchronized:"
            log "    ${relpath}"
            return 0
        fi


        log "WARNING: rsync failed."
        log "    Source    : ${src}"
        log "    Exit code : ${rc}"
        log "Trying next mirror."

    done


    log "ERROR: All mirrors failed for:"
    log "       ${relpath}"

    return 1
}


#
# Overall return value.
#
RETVAL=0


#
# Fedora release repository.
#
# Deliberately NO --delete.
#
# A Fedora release tree should normally be immutable. If an upstream
# mirror becomes incomplete, existing local files are preserved.
#
sync_repo \
    "releases/${RELEASE}/Everything/x86_64/os" \
    "${DEST_BASE}/releases/${RELEASE}/Everything/x86_64/os" \
    "no"

if [ "$?" -ne 0 ]; then
    RETVAL=1
fi


#
# Fedora updates repository.
#
# Superseded RPMs disappear upstream, so deletion is appropriate.
#
# Before the real rsync:
#
#   1. repomd.xml is checked.
#   2. Packages/ structure is checked.
#   3. A complete rsync dry-run is performed.
#   4. Proposed file deletions are counted.
#   5. The source is rejected if MAX_DELETE_PERCENT is exceeded.
#
sync_repo \
    "updates/${RELEASE}/Everything/x86_64" \
    "${DEST_BASE}/updates/${RELEASE}/Everything/x86_64" \
    "yes"

if [ "$?" -ne 0 ]; then
    RETVAL=1
fi


#
# Optional:
#
# createrepo -q --update --workers 10 \
#     "${DEST_BASE}/updates/${RELEASE}/Everything/x86_64/"
#


if [ "$RETVAL" -ne 0 ]; then

    error_msg="$0 returned an error"

    log "$error_msg"
    logger -t "mirror-fedora-${RELEASE}" "$error_msg"

else

    log "------------------------------------------------------------"
    log "Fedora ${RELEASE} synchronization completed successfully."

fi


exit "$RETVAL"