#!/bin/bash
# LUKS passphrase validation hook
# This script runs after installation to verify encryption passphrase strength
set -euo pipefail

echo "Validating LUKS encryption passphrase..."

# Function to check passphrase strength
check_passphrase_strength() {
    local passphrase="$1"
    local issues=0

    # Check minimum length (14 characters)
    if [ ${#passphrase} -lt 14 ]; then
        echo "ERROR: Passphrase is too short (minimum 14 characters)"
        issues=$((issues + 1))
    fi

    # Check for character classes
    has_upper=$(echo "$passphrase" | grep -c '[A-Z]' || true)
    has_lower=$(echo "$passphrase" | grep -c '[a-z]' || true)
    has_digit=$(echo "$passphrase" | grep -c '[0-9]' || true)
    has_special=$(echo "$passphrase" | grep -c '[^A-Za-z0-9]' || true)

    if [ "$has_upper" -eq 0 ]; then
        echo "WARNING: Passphrase should contain uppercase letters"
        issues=$((issues + 1))
    fi

    if [ "$has_lower" -eq 0 ]; then
        echo "WARNING: Passphrase should contain lowercase letters"
        issues=$((issues + 1))
    fi

    if [ "$has_digit" -eq 0 ]; then
        echo "WARNING: Passphrase should contain digits"
        issues=$((issues + 1))
    fi

    if [ "$has_special" -eq 0 ]; then
        echo "WARNING: Passphrase should contain special characters"
        issues=$((issues + 1))
    fi

    # Check for common weak patterns
    if echo "$passphrase" | grep -qiE 'password|secret|admin|root|knel|football|12345|qwerty'; then
        echo "ERROR: Passphrase contains common words or patterns"
        issues=$((issues + 1))
    fi

    return $issues
}

# Check if cryptsetup is available
if ! command -v cryptsetup &> /dev/null; then
    echo "WARNING: cryptsetup not found - cannot validate passphrase"
    exit 0
fi

# Check if encrypted device exists
if [ ! -e /dev/mapper/cryptroot ]; then
    echo "WARNING: Encrypted device not found - skipping validation"
    exit 0
fi

# Get LUKS container device (typically /dev/sda3 for LVM setup)
LUKS_DEVICE=$(dmsetup info cryptroot | grep "Major:" | head -1)
echo "LUKS device info: $LUKS_DEVICE"

# Check encryption details
echo ""
echo "Encryption Status:"
echo "=================="
cryptsetup status cryptroot
echo ""

# Get cipher information
echo "Encryption Details:"
echo "=================="
cryptsetup luksDump /dev/sda3 2>/dev/null | head -30 || true
echo ""

# Check if we can determine passphrase strength from entropy
# This is an approximation - we can't actually read the passphrase
echo ""
echo "Passphrase Strength Validation:"
echo "============================"

# Since we can't directly test the passphrase without unlocking,
# we can only verify the encryption is properly configured
echo "NOTE: Unable to verify passphrase strength directly"
echo "      The encryption passphrase was set during installation."
echo ""
echo "      REQUIREMENTS for LUKS passphrase:"
echo "      - Minimum 14 characters"
echo "      - Mix of uppercase and lowercase letters"
echo "      - Include digits (0-9)"
echo "      - Include special characters (!@#$%^&*)"
echo "      - Avoid common words, patterns, or personal information"
echo ""
echo "      The passphrase is REQUIRED at every system boot."
echo "      Losing this passphrase will result in permanent data loss."
echo ""

# Create a warning file in the user's home directory
if [ -d /home/football ]; then
    cat > /home/football/ENCRYPTION-PASSPHRASE-REMINDER.txt <<'EOF'
================================================================================
KNEL-Football Secure OS - ENCRYPTION PASSPHRASE REMINDER
================================================================================

CRITICAL: Your system uses full disk encryption with LUKS2.

The encryption passphrase you set during installation is required EVERY TIME
the system boots. Without it, the system is completely inaccessible.

PASSPHRASE REQUIREMENTS:
- Minimum 14 characters (strongly recommended: 20+ characters)
- Mix of uppercase and lowercase letters
- Include digits (0-9)
- Include special characters (!@#$%^&*)
- Avoid common words, patterns, or personal information

SECURITY NOTES:
- Store this passphrase in a secure password manager
- Never share this passphrase
- Never write it down in plaintext
- Consider creating a recovery key in an additional LUKS key slot

IF YOU LOSE YOUR PASSPHRASE:
- There is NO backdoor or recovery method
- You MUST have the passphrase to boot the system
- Without the passphrase, ALL DATA IS PERMANENTLY LOST
- Reinstallation will be required (data loss)

KEY MANAGEMENT:
To manage encryption keys (as root):
- Check status: /usr/local/bin/check-encryption.sh
- Manage keys: /usr/local/bin/manage-encryption-keys.sh

DOCUMENTATION:
- See /var/backups/keys/README.txt for detailed information
- Review PRD.md for security requirements
================================================================================
EOF
    # Add installation date after heredoc (variable expansion)
    echo "" >> /home/football/ENCRYPTION-PASSPHRASE-REMINDER.txt
    echo "Date of installation: $(date)" >> /home/football/ENCRYPTION-PASSPHRASE-REMINDER.txt
    chown football:football /home/football/ENCRYPTION-PASSPHRASE-REMINDER.txt
    chmod 600 /home/football/ENCRYPTION-PASSPHRASE-REMINDER.txt

    echo "Encryption reminder created: ~/ENCRYPTION-PASSPHRASE-REMINDER.txt"
fi

# Add to motd for display on login
if [ -f /etc/update-motd.d/99-encryption ]; then
    cat > /etc/update-motd.d/99-encryption <<'EOF'
#!/bin/sh
cat <<'EOT'

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  KNEL-Football Secure OS - Full Disk Encryption Active
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  Your system is protected with LUKS2 full disk encryption.
  Encryption passphrase required at every boot.

  Check encryption status: /usr/local/bin/check-encryption.sh
  Manage encryption keys: /usr/local/bin/manage-encryption-keys.sh

  IMPORTANT: Losing your encryption passphrase will result in
  permanent data loss. Store it securely!

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EOT
EOF
    chmod +x /etc/update-motd.d/99-encryption
fi

# Create systemd service to display encryption status on first boot
cat > /etc/systemd/system/knel-encryption-firstboot.service <<'EOF'
[Unit]
Description=KNEL-Football Encryption First Boot Check
After=local-fs.target cloud-init.target
ConditionPathExists=!/var/lib/knel-encryption-firstboot-done

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

[Install]
WantedBy=multi-user.target
EOF

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

# Create first boot check script
cat > /usr/local/bin/firstboot-encryption-check.sh <<'EOF'
#!/bin/bash
# First boot encryption check and reminder
set -euo pipefail

# Mark as done
touch /var/lib/knel-encryption-firstboot-done

echo ""
echo "================================================================================"
echo "  KNEL-Football Secure OS - First Boot"
echo "================================================================================"
echo ""
echo "  ✓ Full disk encryption is active and verified"
echo "  ✓ System security hardening complete"
echo ""
echo "  IMPORTANT INFORMATION:"
echo "  - Your encryption passphrase is required at every system boot"
echo "  - Store your passphrase securely in a password manager"
echo "  - Never share your passphrase with anyone"
echo "  - Losing your passphrase will result in permanent data loss"
echo ""
echo "  See ~/ENCRYPTION-PASSPHRASE-REMINDER.txt for detailed information"
echo ""
echo "================================================================================"
echo ""
EOF

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

echo ""
echo "LUKS encryption validation completed."
echo "Encryption reminder files created for user reference."
