#!/bin/bash

set -e
set -x

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') $1" | tee -a test.log
}

# Create test directory structure
TEST_DIR="$HOME/test-archive"
MOCK_UPSTREAM="/srv/mock-upstream"  # Mock the remote archive
mkdir -p "$TEST_DIR"
mkdir -p "$TEST_DIR/repos"
mkdir -p "$TEST_DIR/packages"
mkdir -p "$MOCK_UPSTREAM/core/os/x86_64"
mkdir -p "$MOCK_UPSTREAM/extra/os/x86_64"

# Create some test packages in mock upstream
echo "test package 1" > "$MOCK_UPSTREAM/core/os/x86_64/test-1.0-1-x86_64.pkg.tar.zst"
echo "test package 2" > "$MOCK_UPSTREAM/extra/os/x86_64/test-2.0-1-x86_64.pkg.tar.zst"

# Update test config to use local path instead of rsync
cat > /tmp/archive.conf << EOF
ARCHIVE_RSYNC="$MOCK_UPSTREAM/"
ARCHIVE_DIR="$TEST_DIR"
ARCHIVE_USER=$(id -u -n)
ARCHIVE_GROUP=$(id -g -n)
PKGREGEX='\.pkg\.tar(\.(gz|bz2|xz|zst|lrz|lzo|Z|lz4|lz))?'
PKGSIGREGEX="\$PKGREGEX\.sig"
UMASK=022
ARCHIVE_REPO=1
REPO_DAYLY=1
REPO_PACKAGES=1
REPO_PACKAGES_INDEX=1
REPO_PACKAGES_FULL_SEARCH=0
REPO_RSYNC_TIMEOUT=3600
ARCHIVE_ISO=0
EOF

export ARCHIVE_CONFIG=/tmp/archive.conf

# Wrap archive.sh to add logging
run_archive() {
    log "  -> Starting archive.sh"
    # Run archive.sh with debug output
    (
        set -x
        DEBUG=1 ./archive.sh 2>&1 | while IFS= read -r line; do
            log "    $line"
        done
    )
    local status=$?
    log "  -> archive.sh finished with status $status"
    return $status
}

# Test Suite
run_tests() {
    log "==> Starting test suite"
    log "==> Using test directory: $TEST_DIR"
    log "==> Using config: $ARCHIVE_CONFIG"

    log "==> Test 1: Basic archive sync"
    log "  -> Running archive.sh"
    run_archive
    log "  -> Archive sync completed"
    
    log "==> Test 2: Verify archive structure"
    log "  -> Checking repos directory"
    test -d "$TEST_DIR/repos" || (log "ERROR: repos directory missing" && exit 1)
    log "  -> Checking packages directory"
    test -d "$TEST_DIR/packages" || (log "ERROR: packages directory missing" && exit 1)
    log "  -> Directory structure verified"
    
    log "==> Test 3: Test archive-cleaner"
    log "  -> Running archive-cleaner"
    ./archive-cleaner --repo "$TEST_DIR/repos/last" --archive "$TEST_DIR" --keep-years 1
    log "  -> Archive cleaner completed"
    
    log "==> Test 4: Test incremental sync"
    log "  -> Adding new test package"
    echo "new package" > /srv/archive/repos/2024/03/20/core/os/x86_64/test-2.0-1-x86_64.pkg.tar.zst
    log "  -> Running incremental sync"
    run_archive
    log "  -> Incremental sync completed"
    
    log "==> Test 5: Test hardlinking"
    log "  -> Checking for hardlinks"
    find "$TEST_DIR" -type f -links +1 || (log "ERROR: No hardlinks found" && exit 1)
    log "  -> Hardlinks verified"

    # Show final archive structure
    log "==> Final archive structure:"
    find "$TEST_DIR" -type f -exec ls -l {} \;
}

# Run tests
run_tests

log "==> All tests passed!"
log "==> Test log available at: $(pwd)/test.log" 