print("""
-----------------------------------------------------------------
✨ Starting up Barretthousen stack
-----------------------------------------------------------------
""".strip())

load('ext://helm_resource', 'helm_resource', 'helm_repo')
load('ext://deployment', 'deployment_create')
load('ext://restart_process', 'docker_build_with_restart')
load('ext://uibutton', 'cmd_button', 'location', 'text_input')

helm_repo('bitnami', 'https://charts.bitnami.com/bitnami', labels=["9-repos"])
helm_repo('traefik', 'https://traefik.github.io/charts', labels=["9-repos"])
helm_repo('grafana', 'https://grafana.github.io/helm-charts', labels=["9-repos"])

helm_resource(
    'ingress',
    'traefik/traefik',
    namespace='barretthousen-local',
    flags=[
        '--set', 'logs.access.enabled=true'
    ],
    port_forwards=[
        port_forward(8000, 8000, name="Traefik HTTP :8000"),
        port_forward(9000, 9000, name='Traefik Dashboard', link_path='/dashboard/#/')
    ],
    resource_deps=['traefik'],
    labels=["1-ingress"]
)

k8s_resource(
    workload='ingress',
    labels='1-ingress',
    links=[
        link(url='http://admin.localhost:8000', name='admin.localhost'),
        link(url='http://bh.localhost:8000', name='bh.localhost'),
    ]
)

helm_resource(
    'postgres',
    'bitnami/postgresql',
    namespace='barretthousen-local',
    flags=[
        '--set', 'fullnameOverride=bh-db',
        '--set', 'auth.enablePostgresUser=true',
        '--set', 'auth.postgresPassword=bh-admin',
        '--set', 'auth.database=bh',
    ],
    port_forwards=[port_forward(5432, 5432, name='BH DB')],
    resource_deps=['bitnami'],
    labels=["9-data"]
)

def bh_client(service="", port_forwards=[], labels=['2-services'], deps=['ingress']):
    basepath = './src/{}-client'.format(service)
    docker_build(
        ref='barretthousen/client-{}-client'.format(service),
        context=basepath,
        dockerfile='./src/Dockerfile.frontend'.format(service),
        target='development',
        build_args={
            "service": '{}-client'.format(service)
        },
        entrypoint='vite dev --port=80 --host=0.0.0.0 --strictPort --logLevel info',
        live_update=[
            sync(basepath + '/src', '/opt/{}-client/src'.format(service)),
            sync(basepath + '/static', '/opt/{}-client/static'.format(service)),
            run('cd {} && npm install'.format(basepath), trigger=[basepath+'/package.json', basepath+'/package.lock.json'])
        ]
    )

    k8s_resource(
        workload='{}-client-local'.format(service),
        port_forwards=port_forwards,
        labels=['2-services'],
        resource_deps=deps
    )

def bh_backend_service(service="", port_forwards=[], migrateDB=False, devMode=True, labels=['2-services'], deps=['postgres']):
    local_resource(
        '{}-go-compile'.format(service),
        'CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -gcflags "all=-N -l" -o .bin/{}-debug ./src/{}'.format(service, service),
        deps=['./src/{}'.format(service), './src/lib'],
        labels=['3-compilation']
    )

    # complains about grpc port still being in use, so maybe the service isn't exiting cleanly
    entry_cmd = [
            '/go/bin/dlv',
            '--headless',
            '--listen=0.0.0.0:2345',
            '--api-version=2',
            '--log',
            '--accept-multiclient',
            '--log-output=rpc',
            'exec',
            '/opt/{}-debug'.format(service),
            '--continue'
        ]

    if migrateDB:
        entry_cmd += ['--', '-migrate']

    docker_build_with_restart(
        ref="barretthousen/service-{}".format(service),
        dockerfile="./src/Dockerfile.dev-backend",
        context=".",
        entrypoint=entry_cmd,
        build_args={
            "service": service
        },
        trigger = [
            './.bin/{}-debug'.format(service)
        ],
        only = [
            './.bin/{}-debug'.format(service),
            './src/runner',
            './src/catalog',
            './src/proxy-admin',
            './src/proxy-web',
            './src/lib'
        ],
        live_update=[
            sync('./.bin', '/opt'),
            sync('./src', '/go/src'),
        ]
    )

    k8s_resource(
        workload='{}-local'.format(service),
        port_forwards=port_forwards,
        labels=labels,
        resource_deps=deps,
    )


k8s_yaml(
    kustomize("./env/local")
)

k8s_resource(
    workload='runner-sync-local',
    labels='2-services'
)


bh_backend_service(service="auth", migrateDB=True, port_forwards=[
    port_forward(2345, name='Delve port')
])

bh_backend_service(service="runner", migrateDB=True, port_forwards=[
    port_forward(2346, 2345, name='Delve port')
])

bh_backend_service(service="catalog", migrateDB=True, port_forwards=[
    port_forward(2347, 2345, name='Delve port')
])

bh_backend_service(service="proxy-admin", port_forwards=[
    port_forward(8082, 80, name="HTTP API @ localhost:8082")
], deps=['ingress'])

bh_backend_service(service="proxy-web", port_forwards=[
    port_forward(8081, 80, name="HTTP API @ localhost:8081")
], deps=['ingress'])

bh_client(service='web', deps=["proxy-web-local"])
bh_client(service='admin', deps=["proxy-admin-local"])

createAdminCmd = [
    './hack/create_user.sh', 'admin@barretthousen.com', 'admin', 'ADMINISTRATOR'
]

loginAdminCmd = [
    'curl', '-vvvv', '-X POST', '-H "Content-Type: application/json"',
    '-d "{\"email\":\"admin@barretthousen.com\", \"password\":\"admin\"}"',
    'http://bh.localhost:8000/api/v1/user'
]

syncCatalogsCmd = [
    'curl', '-vvvv', '-X', 'PUT',
    '-H', 'Content-Type: application/json',
    '-H', 'bh-session-id: 2',
    '-d', '{\"targetSite\":\"All\"}',
    'http://admin.localhost:8000/api/v1/sync'
]

local(createAdminCmd, quiet=False, echo_off=True)
local(loginAdminCmd, quiet=False, echo_off=True)
local(syncCatalogsCmd, quiet=False, echo_off=True)

cmd_button(
    name='Sync Catalogs',
    argv=syncCatalogsCmd,
    text='Sync Catalogs',
    location=location.NAV,
    icon_name='sync')


