#!/bin/bash
# Full disk encryption setup for installed system
# This hook configures encryption settings and ensures proper LUKS setup
set -euo pipefail

echo "Configuring full disk encryption..."

# Ensure cryptsetup is installed
if ! command -v cryptsetup &> /dev/null; then
    echo "ERROR: cryptsetup not found - critical failure"
    exit 1
fi

# Configure LUKS2 settings
echo "Configuring LUKS2 with AES-256-XTS encryption..."

# Create cryptsetup configuration for maximum security
cat > /etc/cryptsetup-initramfs/conf-hook <<'EOF'
# Enable keyscripts in initramfs
CRYPTSETUP=y

# Use LUKS2 format
KEYSCRIPT=y

# Enable keyscript support
CRYPTSETUP_OPTIONS=--type luks2
EOF

# Configure crypttab for encrypted root
# This file will be generated by the installer, but we ensure proper settings
if [ -f /etc/crypttab ]; then
    echo "Verifying crypttab configuration..."
    # Ensure crypttab has proper options
    sed -i 's/luks$/luks,discard,cipher=aes-xts-plain64,key-size=512/g' /etc/crypttab
fi

# Configure initramfs to include necessary modules for decryption
cat > /etc/initramfs-tools/conf.d/cryptsetup <<'EOF'
# Ensure cryptsetup modules are included
MODULES=dm_crypt

# Include busybox for initramfs
BUSYBOX=y

# Include cryptsetup
CRYPTSETUP=y
EOF

# Add cryptsetup and dm-crypt to initramfs modules
{
    echo "dm_crypt"
    echo "aes_xts"
    echo "xts"
    echo "sha512"
} >> /etc/initramfs-tools/modules

# Configure kernel command line for encrypted root
if [ -f /etc/default/grub ]; then
    echo "Configuring GRUB for encrypted root..."
    # Get the current GRUB_CMDLINE_LINUX_DEFAULT
    if ! grep -q "cryptdevice" /etc/default/grub; then
        # This will be set by the installer, but we ensure proper format
        # Note: We use a placeholder UUID that will be updated by the installer
        # The actual UUID of the encrypted root will be determined at install time
        sed -i '/^GRUB_CMDLINE_LINUX_DEFAULT=/s/"$/ rd.luks.crypttab=1"/' /etc/default/grub || true
    fi
fi

# Set secure umask for key files
umask 0077

# Create key backup directory
mkdir -p /var/backups/keys
chmod 700 /var/backups/keys

# Create README for key recovery
cat > /var/backups/keys/README.txt <<'EOF'
KNEL-Football Secure OS - Encryption Key Backup Information
=============================================================

CRITICAL: This system uses full disk encryption with LUKS2.

Encryption Details:
- Format: LUKS2
- Cipher: AES-256-XTS
- Key Size: 512 bits
- Hash: SHA-512
- KDF: Argon2id

Key Slots:
- Slot 0: Primary passphrase (set during installation)
- Slot 1-7: Available for recovery keys or additional passphrases

Recovery Information:
- Store encryption passphrase in secure location
- Document passphrase in password manager
- Consider creating recovery key in secondary slot

Commands:
- Check encryption status: cryptsetup status cryptroot
- Add additional passphrase: cryptsetup luksAddKey /dev/sda3
- List key slots: cryptsetup luksDump /dev/sda3

WARNING: Losing the encryption passphrase will result in
permanent data loss. There is NO backdoor or recovery mechanism
without a valid passphrase or recovery key.

DO NOT remove this file - it contains critical recovery information.
EOF

chmod 600 /var/backups/keys/README.txt

# Create encryption status script
cat > /usr/local/bin/check-encryption.sh <<'EOF'
#!/bin/bash
# Check full disk encryption status
set -euo pipefail

echo "KNEL-Football Full Disk Encryption Status"
echo "========================================="
echo ""

# Check if cryptsetup is available
if ! command -v cryptsetup &> /dev/null; then
    echo "ERROR: cryptsetup not found"
    exit 1
fi

# List all encrypted devices
echo "Encrypted Devices:"
echo "-----------------"
for dev in /dev/mapper/*; do
    if [ -e "$dev" ]; then
        echo "$dev"
        dmsetup info "$dev" | grep -E "(Name|Open count|Target)"
    fi
done
echo ""

# Check LUKS container details
if [ -b /dev/sda3 ]; then
    echo "LUKS Container Information:"
    echo "---------------------------"
    cryptsetup luksDump /dev/sda3 | head -20
    echo ""
fi

# Check encryption is active
if mountpoint -q /; then
    echo "Root filesystem encryption: ACTIVE"
else
    echo "Root filesystem encryption: UNKNOWN"
fi

echo ""
echo "Encryption: AES-256-XTS (LUKS2)"
echo "Status: Full disk encryption enabled"
EOF

chmod +x /usr/local/bin/check-encryption.sh

# Create encryption key management script
cat > /usr/local/bin/manage-encryption-keys.sh <<'EOF'
#!/bin/bash
# Manage LUKS encryption keys
set -euo pipefail

echo "KNEL-Football Encryption Key Management"
echo "========================================"
echo ""

# Check root privileges
if [ "$EUID" -ne 0 ]; then
    echo "ERROR: This script must be run as root"
    exit 1
fi

# List options
echo "Select an option:"
echo "1. Add new passphrase to key slot"
echo "2. Remove passphrase from key slot"
echo "3. Change primary passphrase"
echo "4. List active key slots"
echo "5. Generate recovery key"
echo "0. Exit"
echo ""
read -p "Enter selection [0-5]: " choice

case $choice in
    1)
        read -s -p "Enter existing passphrase: " existing_pass
        echo ""
        read -s -p "Enter new passphrase: " new_pass
        echo ""
        read -s -p "Confirm new passphrase: " new_pass_confirm
        echo ""

        if [ "$new_pass" != "$new_pass_confirm" ]; then
            echo "ERROR: Passphrases do not match"
            exit 1
        fi

        echo "$existing_pass" | cryptsetup luksAddKey /dev/sda3 - <<< "$new_pass"
        echo "New passphrase added successfully"
        ;;
    2)
        cryptsetup luksDump /dev/sda3 | grep "Key Slot"
        read -p "Enter key slot to remove: " slot
        cryptsetup luksKillSlot /dev/sda3 "$slot"
        echo "Key slot removed successfully"
        ;;
    3)
        echo "WARNING: Changing primary passphrase"
        read -s -p "Enter current passphrase: " current_pass
        echo ""
        read -s -p "Enter new passphrase: " new_pass
        echo ""
        read -s -p "Confirm new passphrase: " new_pass_confirm
        echo ""

        if [ "$new_pass" != "$new_pass_confirm" ]; then
            echo "ERROR: Passphrases do not match"
            exit 1
        fi

        # This is complex and requires careful handling
        echo "This operation requires manual intervention"
        echo "Please use: cryptsetup luksChangeKey /dev/sda3"
        ;;
    4)
        echo "Active key slots:"
        cryptsetup luksDump /dev/sda3 | grep "Key Slot" | grep "ENABLED"
        ;;
    5)
        echo "Generating recovery key..."
        # Generate a strong random key
        dd if=/dev/urandom bs=1 count=32 2>/dev/null | base64 > /var/backups/keys/recovery_key_$(date +%Y%m%d_%H%M%S).txt
        chmod 600 /var/backups/keys/recovery_key_*.txt
        echo "Recovery key generated and stored in /var/backups/keys/"
        echo "WARNING: Store this key in a secure, offline location"
        ;;
    0)
        echo "Exiting"
        exit 0
        ;;
    *)
        echo "Invalid selection"
        exit 1
        ;;
esac
EOF

chmod +x /usr/local/bin/manage-encryption-keys.sh

# Configure system to check encryption on boot
cat > /etc/systemd/system/knel-encryption-check.service <<'EOF'
[Unit]
Description=KNEL-Football Encryption Status Check
After=local-fs.target
ConditionPathExists=/usr/local/bin/check-encryption.sh

[Service]
Type=oneshot
ExecStart=/usr/local/bin/check-encryption.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

systemctl enable knel-encryption-check.service || true

echo "Full disk encryption configuration completed."
echo "Encryption: LUKS2 with AES-256-XTS"
echo "Key management scripts installed in /usr/local/bin/"
