#!/usr/bin/env python3

import asyncio
import sys
import os
import argparse
import json
import yaml
home = os.path.expanduser("~")

def generatejson(args, listofargs):
    document = f"""---
                 apiVersion: v1
                 kind: Pod
                 metadata:
                   name: {args.image}-app
                   labels:
                     app: web
                 spec:
                   containers:
                     - name: {args.image}
                       image: jozzy008/{args.image}:{args.version}
                       args: {listofargs[4:]}
                       ports:
                         - containerPort: 80
                """
    if not os.path.exists(f"{home}/bzctl/config"): os.mkdir(f"{home}/bzctl/config")

    with open(f'{home}/bzctl/config/{args.image}.json', 'w', encoding='utf-8') as f:
        json.dump(yaml.load(document, Loader=yaml.FullLoader),
                  f, ensure_ascii=False, indent=4)


def run(args):
    listofargs = []
    print("Given arguments: ")
    for argss in sys.argv[2:]:
        listofargs.append(argss)
        print(argss)

    generatejson(args, listofargs)

    token = input("Please enter your decoded bearer token...\n")
    os.system(
        f'curl -k -v \
            -X POST \
            -H "Authorization: Bearer {token}" \
            -H "Content-Type: application/json" \
            http://127.0.0.1:8080/api/v1/namespaces/default/pods -d@{home}/bzctl/config/{args.image}.json')


def delete(args):
    listofargs = []
    print("Given arguments: ")
    for argss in sys.argv[2:]:
        listofargs.append(argss)
        print(argss)

    token = input("Please enter your decoded bearer token for deletein...\n")
    os.system(
        f'curl -k \
            -X DELETE \
            -H "Authorization: Bearer {token}" \
            -H "Content-Type: application/json" \
            http://127.0.0.1:8080/api/v1/namespaces/default/pods/{args.image}-app')

    


def main():

    if not os.path.isdir(f"{home}/bzctl"): os.makedirs(f"{home}/bzctl")
    


    if len(sys.argv) > 1 and sys.argv[1][0] != '-':

        if sys.argv[1] == 'run':
            sys.argv[1] = "---run"

        if sys.argv[1] == 'delete':
            sys.argv[1] = "---delete"

    PARSER = argparse.ArgumentParser()

# region PARSER
    PARSER.add_argument(
        '---run',               help='Use this if you want to deploy a pod', action='store_true')
    PARSER.add_argument(
        '---delete',            help='Use this if you want to delete a pod', action='store_true')
    PARSER.add_argument(
        '--image',              help="Specify the image's name that will be pulled", type=str)
    PARSER.add_argument(
        '--version',            help="Specify the image's version that will be pulled", type=str)
    PARSER.add_argument(
        '--http',               help='This is a geth command. Enable the HTTP-RPC server', action='store_true')
    PARSER.add_argument('--http.corsdomain',
                        help='Comma separated list of domains from which to accept cross origin requests (browser enforced)', type=str)
    PARSER.add_argument('--http.api',
                        help="API's offered over the HTTP-RPC interface", type=str)
    PARSER.add_argument(
        '--rpc',                help="Enable the HTTP-RPC server (deprecated and will be removed June 2021, use --http)", action='store_true')
    PARSER.add_argument('--rpccorsdomain',      help="Comma separated list of domains from which to accept cross origin requests (browser enforced) (deprecated and will be removed June 2021, use --http.corsdomain)", type=str)
# endregion

    args = PARSER.parse_args()

    if args.run:
        run(args)

    if args.delete:
        delete(args)


main()
