#!/usr/bin/env python3
import argparse
import sys
import os
import importlib.resources

from sentipede.web_server import WebExfil
from sentipede.ui import display_art, gradient_text


def get_current_version():
    try:
        ref = importlib.resources.files("sentipede").joinpath("version.txt")
        with importlib.resources.as_file(ref) as path:
            return path.read_text().strip()
    except Exception:
        return "unknown"


def main():
    parser = argparse.ArgumentParser(
        description="Sentipede: A simple HTTP file server for exfiltration/infiltration.",
        formatter_class=argparse.RawTextHelpFormatter
    )

    parser.add_argument(
        "-p", "--port",
        type=int,
        default=8000,
        metavar="PORT",
        help="Port to run the server on (default: 8000)"
    )

    parser.add_argument(
        "-d", "--directory",
        type=str,
        default=".",
        metavar="DIR",
        help="Directory to serve files from (default: current directory)"
    )

    parser.add_argument(
        "--version",
        action="store_true",
        help="Display the current version of Sentipede"
    )

    args = parser.parse_args()
    current_version = get_current_version()

    if args.version:
        print(f"🐛 Sentipede version: {gradient_text(current_version)}")
        sys.exit(0)

    directory = os.path.abspath(args.directory)

    if not os.path.exists(directory):
        print(f"Error: Directory '{directory}' does not exist", file=sys.stderr)
        sys.exit(1)

    if not os.path.isdir(directory):
        print(f"Error: '{directory}' is not a directory", file=sys.stderr)
        sys.exit(1)

    display_art()

    server = WebExfil(directory=directory, port=args.port)
    server.run()


def run():
    try:
        main()
    except KeyboardInterrupt:
        print(f"\n\n{gradient_text('🐛 Sentipede stopped by user. Goodbye!')}")
        sys.exit(0)


if __name__ == "__main__":
    run()