from flask import Flask, render_template, request, redirect, url_for
import subprocess
import re
from waitress import serve

allowed_pattern = r'^[a-zA-Z0-9.]+$'

def is_valid_input(input_string):
    return re.match(allowed_pattern, input_string) is not None

app = Flask(__name__)

def create_email_account(username, password):
    if is_valid_input(password) and is_valid_input(username):
        try:
            # Use echo to securely pass the password to the command
            cmd = ["echo", password, "|", "doas", "-u", "maddy", "maddy", "creds", "create", f"{username}@hectabit.org"]
            result = subprocess.run(" ".join(cmd), shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

            cmd2 = ["doas", "-u", "maddy", "maddy", "imap-acct", "create", f"{username}@hectabit.org"]
            result2 = subprocess.run(" ".join(cmd2), shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

            if result.returncode == 0 and result2.returncode == 0:
                # Command executed successfully
                return True
            else:
                # Handle errors, log them, and return False
                error_message = result.stderr.decode("utf-8")
                print(f"Error creating email account: {error_message}")
                return False
        except Exception as e:
            # Handle exceptions and return False
            print(f"Error creating email account: {str(e)}")
            return False
    else:
        print(f"Injection Bypass! Very bad!")
        return False

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api', methods=['POST'])
def register():
    username = request.form.get('username')
    password = request.form.get('password')

    if not is_valid_input(password) or not is_valid_input(username):
        return render_template('num.html'), 400

    if create_email_account(username, password):
        return render_template('ok.html')
    else:
        return render_template('err.html'), 500


if __name__ == '__main__':
    serve(app, host='0.0.0.0', port=8050)
