#!/usr/bin/env python3
"""
Backdrops Premium Bypass - Interactive Controller
CTF Challenge - Dynamic Analysis Tool

Usage:
    python backdoors_controller.py
"""

import frida
import sys
import time

PACKAGE_NAME = "com.backdrops.wallpapers"
SCRIPT_PATH = "frida_backdrops_bypass.js"

def on_message(message, data):
    """Handle messages from Frida script"""
    if message['type'] == 'send':
        print(f"[*] {message['payload']}")
    elif message['type'] == 'error':
        print(f"[!] Error: {message['stack']}")

def main():
    print("=" * 70)
    print("    Backdrops Premium Bypass - Interactive Controller")
    print("    CTF Challenge - Dynamic Analysis")
    print("=" * 70)
    print()
    
    try:
        # Get USB device
        print("[*] Connecting to USB device...")
        device = frida.get_usb_device()
        print(f"[+] Connected to: {device}")
        
        # Check if app is running
        try:
            print(f"[*] Looking for {PACKAGE_NAME}...")
            session = device.attach(PACKAGE_NAME)
            print(f"[+] Attached to running app")
        except frida.ProcessNotFoundError:
            print(f"[*] App not running, spawning...")
            pid = device.spawn([PACKAGE_NAME])
            session = device.attach(pid)
            device.resume(pid)
            print(f"[+] Spawned and attached to app (PID: {pid})")
        
        # Load Frida script
        print(f"[*] Loading script: {SCRIPT_PATH}...")
        with open(SCRIPT_PATH, 'r', encoding='utf-8') as f:
            script_code = f.read()
        
        script = session.create_script(script_code)
        script.on('message', on_message)
        script.load()
        print("[+] Script loaded successfully!")
        print()
        
        # Wait for hooks to initialize
        time.sleep(2)
        
        # Interactive menu
        while True:
            print("\n" + "=" * 70)
            print("  MENU")
            print("=" * 70)
            print("  1. List current purchase status")
            print("  2. Inject fake purchase (manual SKU)")
            print("  3. Inject all premium packs")
            print("  4. Toggle bypass ON/OFF")
            print("  5. Show SKU list")
            print("  6. Monitor mode (just watch console)")
            print("  0. Exit")
            print("=" * 70)
            
            choice = input("\nEnter choice: ").strip()
            
            if choice == '1':
                print("\n[*] Listing purchases...")
                try:
                    result = script.exports.listpurchases()
                    print(result)
                except Exception as e:
                    print(f"[!] Error: {e}")
                    
            elif choice == '2':
                sku = input("Enter SKU to inject: ").strip()
                print(f"\n[*] Injecting purchase for: {sku}")
                try:
                    result = script.exports.injectpurchase(sku)
                    print(f"[+] Result: {result}")
                except Exception as e:
                    print(f"[!] Error: {e}")
                    
            elif choice == '3':
                print("\n[*] Injecting all premium packs...")
                skus = [
                    "premium.pack.trinity",
                    "premium.pack.amoled",
                    "premium.pro",
                    "premium.pack.acid",
                    "premium.pack.optic",
                    "premium.pack.void",
                    "premium.pack.synth"
                ]
                for sku in skus:
                    try:
                        script.exports.injectpurchase(sku)
                        print(f"  [+] Injected: {sku}")
                    except Exception as e:
                        print(f"  [!] Failed {sku}: {e}")
                print("[+] Done!")
                
            elif choice == '4':
                current = input("Enable bypass? (y/n): ").strip().lower()
                enabled = current == 'y'
                try:
                    result = script.exports.togglebypass(enabled)
                    print(f"[+] Bypass is now: {'ENABLED' if result else 'DISABLED'}")
                except Exception as e:
                    print(f"[!] Error: {e}")
                    
            elif choice == '5':
                print("\n[*] Premium SKU List:")
                print("=" * 70)
                skus = {
                    "premium.pack.trinity": "Trinity Pack",
                    "premium.pack.amoled": "AMOLED Pack",
                    "premium.pro": "Pro Subscription",
                    "premium.pack.acid": "Acid Pack",
                    "premium.pack.optic": "Optic Pack",
                    "premium.pack.void": "Void Pack",
                    "premium.pack.synth": "Synth Pack"
                }
                for sku, name in skus.items():
                    print(f"  {sku:30s} - {name}")
                print("=" * 70)
                print("Note: These are estimated SKU names based on code analysis.")
                print("      Actual SKUs will be shown when the app accesses them.")
                
            elif choice == '6':
                print("\n[*] Monitor mode - Press Ctrl+C to return to menu")
                print("[*] Watching for premium checks...\n")
                try:
                    while True:
                        time.sleep(1)
                except KeyboardInterrupt:
                    print("\n[*] Returning to menu...")
                    
            elif choice == '0':
                print("\n[*] Exiting...")
                break
                
            else:
                print("[!] Invalid choice")
        
    except frida.ServerNotStartedError:
        print("[!] Error: Frida server is not running on the device!")
        print("[!] Start frida-server on your Android device:")
        print("    adb shell \"/data/local/tmp/frida-server &\"")
        sys.exit(1)
        
    except frida.TimedOutError:
        print("[!] Error: Connection timed out!")
        print("[!] Make sure USB debugging is enabled and device is connected")
        sys.exit(1)
        
    except FileNotFoundError:
        print(f"[!] Error: Script file not found: {SCRIPT_PATH}")
        print("[!] Make sure the Frida script is in the current directory")
        sys.exit(1)
        
    except KeyboardInterrupt:
        print("\n\n[*] Interrupted by user")
        
    except Exception as e:
        print(f"[!] Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
    
    finally:
        print("[*] Cleanup complete")
        print("[*] Goodbye!")

if __name__ == "__main__":
    main()
