#!/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"
mkdir -p "$TEST_DIR"

# 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"
    ./archive.sh
    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"
    ./archive.sh
    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 {} \;
}

# Setup
log "==> Setting up test environment"
cp test-archive.conf /tmp/archive.conf
export ARCHIVE_CONFIG=/tmp/archive.conf

# Run tests
run_tests

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