#!/usr/bin/env python3
import sys
import re

def extract_userdata(file_path, vm_name, vmid):
    with open(file_path, 'r') as f:
        content = f.read()
    
    # Find the section for this VM
    # Pattern: VM: <name> (VMID: <id>) followed by separator, then userData until next separator
    pattern = rf'VM: {re.escape(vm_name)}.*?VMID: {vmid}.*?==========================================\n(.*?)=========================================='
    match = re.search(pattern, content, re.DOTALL)
    
    if match:
        userdata = match.group(1).strip()
        # Remove any ANSI color codes if present
        userdata = re.sub(r'\x1b\[[0-9;]*m', '', userdata)
        return userdata
    
    # Try alternative pattern without strict VM name match
    pattern2 = rf'VM:.*?VMID: {vmid}.*?==========================================\n(.*?)=========================================='
    match2 = re.search(pattern2, content, re.DOTALL)
    if match2:
        userdata = match2.group(1).strip()
        userdata = re.sub(r'\x1b\[[0-9;]*m', '', userdata)
        return userdata
    
    return ""

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: extract_userdata.py <file> <vm_name> <vmid>", file=sys.stderr)
        sys.exit(1)
    
    file_path = sys.argv[1]
    vm_name = sys.argv[2]
    vmid = sys.argv[3]
    
    userdata = extract_userdata(file_path, vm_name, vmid)
    if userdata:
        print(userdata)

