import click
import subprocess as sp
import os
import shutil

from app.helper import install_available
from decouple import config

@click.group()
def api():
    pass


@api.command("setup")
@click.option("--path", required=True)
@click.option("--auth_name", required=True)
@click.option("--auth_seed", required=True)
@click.option("--auth_realm", required=True)
@click.option("--realm_allowed", multiple=True, required=True)
@click.option("--etcd_url", required=True)
@click.option("--otp_server", default="https://otp.ungleich.ch/ungleichotp/", 
              help="URL of ungleich OTP server")
def setup(path, auth_name, auth_seed, auth_realm,
          realm_allowed, otp_server, etcd_url):
    
    os.chdir(path)

    repo_name = "ucloud-api"
    
    # Clone main repo
    sp.check_output(['git', 'clone', '--single-branch', '--branch', 'wip',
                    f'https://code.ungleich.ch/ungleich-public/{repo_name}.git'])

    # Create .env file
    with open(os.path.join(repo_name, ".env"), "w") as f:
        content = (
            f"AUTH_NAME={auth_name}\n"
            f"AUTH_SEED={auth_seed}\n"
            f"AUTH_REALM={auth_realm}\n"
            f"REALM_ALLOWED={list(realm_allowed)}\n"
            f"OTP_SERVER={otp_server}\n"
            f"ETCD_URL={etcd_url}\n"
            f"VM_PREFIX=/v1/vm\n",
            f"HOST_PREFIX=/v1/host\n",
            f"IMAGE_PREFIX=/v1/image\n",
            f"IMAGE_STORE_PREFIX=/v1/image_store\n",
            f"REQUEST_PREFIX=/v1/request\n",
            f"FILE_PREFIX=/v1/file\n"
        )
        f.writelines(content)
    
    # Clone Common and Etcd Wrapper
    # clone_common(path=repo_name)
    # clone_etcd_wrapper(path=repo_name)

    # Copy Etcd Wrapper inside ucloud_common as ucloud_common
    # also needs etcd wrapper
    # shutil.copytree(
    #     src=os.path.join(repo_name, "etcd3_wrapper"),
    #     dst=os.path.join(repo_name, "ucloud_common", "etcd3_wrapper"),
    # )
    
    install_available(repo_name)
    
    # Create virtualenv with site-packages enabled and install all dependencies
    # sp.check_output(['pipenv','--site-packages', '--three'], cwd=repo_name)
    sp.check_output(['pipenv', 'install'], cwd=repo_name)
    sp.check_output(['pipenv', 'run', 'python', 'create_image_store.py'], cwd=repo_name)