import hashlib
import json
import subprocess

def upload(data):
    json_data = json.dumps(data)
    md5sum = hashlib.md5(json_data.encode('utf-8')).hexdigest()

    # Run rentry client as subprocess
    p = subprocess.Popen(
        ['./services/rentry', 'new', {json_data}],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    # Send JSON data to rentry client
    stdout, stderr = p.communicate(json_data.encode('utf-8'))

    if p.returncode != 0:
        # Rentry client failed
        print(f"Error running rentry client: {stderr.decode('utf-8')}")
        return None

    # Parse JSON response from rentry client
    json_response = json.loads(stdout.decode('utf-8'))

    return {
        "service": "rentry",
        "name": json_response["slug"],
        "key": f"https://rentry.co/{json_response['slug']}",
        "md5sum": md5sum
    }

