#!/bin/bash
# Initialize Restic backup repository on NAS
# Run once to set up the backup system

set -e

# Configuration
BACKUP_REPO="/mnt/nas/backups/homelab-restic"
PASSWORD_FILE="/home/hoborg/creds/restic-password.txt"

echo "========================================"
echo "Restic Backup Repository Initialization"
echo "========================================"
echo ""
echo "This will:"
echo "  1. Install restic if needed"
echo "  2. Create backup repository at: $BACKUP_REPO"
echo "  3. Generate and save encryption password"
echo ""

# Check if restic is installed
if ! command -v restic &> /dev/null; then
    echo "Installing restic..."
    pacman -S --needed --noconfirm restic
    echo "✓ Restic installed"
else
    echo "✓ Restic already installed ($(restic version))"
fi

# Create backup directory on NAS
echo ""
echo "Creating backup directory on NAS..."
mkdir -p "$BACKUP_REPO"
echo "✓ Directory created: $BACKUP_REPO"

# Generate random password if doesn't exist
echo ""
if [ -f "$PASSWORD_FILE" ]; then
    echo "✓ Password file already exists: $PASSWORD_FILE"
else
    echo "Generating encryption password..."
    mkdir -p /home/hoborg/creds
    openssl rand -base64 32 > "$PASSWORD_FILE"
    chmod 600 "$PASSWORD_FILE"
    echo "✓ Password saved to: $PASSWORD_FILE"
    echo "⚠️  IMPORTANT: Back up this password file! Without it, backups cannot be restored."
fi

# Export password for restic
export RESTIC_PASSWORD_FILE="$PASSWORD_FILE"

# Initialize repository
echo ""
echo "Initializing Restic repository..."
if restic -r "$BACKUP_REPO" snapshots &>/dev/null; then
    echo "✓ Repository already initialized"
else
    restic -r "$BACKUP_REPO" init
    echo "✓ Repository initialized"
fi

echo ""
echo "========================================"
echo "Backup Repository Ready!"
echo "========================================"
echo ""
echo "Repository location: $BACKUP_REPO"
echo "Password file: $PASSWORD_FILE"
echo ""
echo "Next steps:"
echo "  1. Run backup-homelab.sh to create first backup"
echo "  2. Test restore with backup-restore.sh"
echo "  3. Enable automated backups with systemd timer"
echo ""
