# Tiltfile for working with Next and Strapi locally


# load('ext://cert_manager', 'deploy_cert_manager')
# deploy_cert_manager()
load('ext://dotenv', 'dotenv')
dotenv(fn='.env')


load('ext://helm_remote', 'helm_remote')
helm_remote(
    'kubernetes-ingress-controller',
    repo_name='kubernetes-ingress-controller',
    repo_url='https://ngrok.github.io/kubernetes-ingress-controller',
    namespace='futureporn',
    create_namespace='false',
    set=[
        'credentials.apiKey=%s' % os.getenv('NGROK_API_KEY'),
        'credentials.authtoken=%s' % os.getenv('NGROK_AUTHTOKEN')
    ]
)

k8s_yaml(helm(
    './charts/fp',
    values=['./charts/fp/values-dev.yaml'],
))



# # docker_build('fp/link2cid', './packages/link2cid')
# docker_build(
#     'fp/strapi',
#     '.',
#     only=["./packages/strapi"],
#     dockerfile='d.strapi.dockerfile',
#     target='release',
#     live_update=[
#         sync('./packages/strapi', '/app')
#     ]
# )

load('ext://uibutton', 'cmd_button')
# @todo in the future we can add a button for seeding the db from scratch.
#       this would be good for onboarding devs
#       step 1 would be creating the db
#

# step 2 is ???
#
#  set -eu
#  # get k8s pod name from tilt resource name
#  POD_NAME="$(tilt get kubernetesdiscovery "$resource" -ojsonpath='{.status.pods[0].name}')"
#  kubectl exec "$POD_NAME" -- $command


pg_seed_script = '''
kubectl -n futureporn exec postgres -- psql -U postgres --command "CREATE DATABASE futureporn_db WITH OWNER = postgres ENCODING = 'UTF8' LOCALE_PROVIDER = 'libc' CONNECTION LIMIT = -1 IS_TEMPLATE = False;"
'''
cmd_button('postgres:seed',
        argv=['sh', '-c', pg_seed_script],
        resource='postgres',
        icon_name='dataset',
        text='seed db with sample data',
)
cmd_button('postgres:restore',
        argv=['sh', '-c', 'cd letters && yarn install'],
        resource='postgres',
        icon_name='cloud_download',
        text='restore db from backup',
)
pgadmin_import_script = '''
    # @todo this script is meant for first-time setup of the cluster
    #       it sets up the UI to have a futureporn postgres server connection
    #
    # @see https://www.pgadmin.org/docs/pgadmin4/development/import_export_servers.html#json-format
    #

    # futureporn.pgadmin.json
    {
        "Servers": {
            "1": {
                "Name": "futureporn",
                "Group": "Servers",
                "Host": "postgres.futureporn.svc.cluster.local",
                "Port": 5432,
                "MaintenanceDB": "postgres",
                "Username": "postgres",
                "UseSSHTunnel": 0,
                "TunnelPort": "22",
                "TunnelAuthentication": 0,
                "KerberosAuthentication": false,
                "ConnectionParameters": {
                    "sslmode": "prefer",
                    "connect_timeout": 10,
                    "sslcert": "<STORAGE_DIR>/.postgresql/postgresql.crt",
                    "sslkey": "<STORAGE_DIR>/.postgresql/postgresql.key"
                }
            }
        }
    }
    kubectl -n futureporn exec pgadmin -- /usr/bin/python /pgadmin/setup.py load-servers futureporn.pgadmin.json
'''
cmd_button('pgadmin:server',
        argv=['sh', '-c', pgadmin_import_script],
        resource='pgadmin',
        icon_name='dataset',
        text='create connection'
)


## Uncomment the following for fp/next in dev mode
## this is useful for changing the UI and seeing results
docker_build(
    'fp/next',
    '.',
    only=['./pnpm-lock.yaml', './package.json', './packages/next'],
    dockerfile='d.next.dockerfile',
    target='dev',
    build_args={
        'NEXT_PUBLIC_STRAPI_URL': 'http://strapi.futureporn.svc.cluster.local:1337'
    },
    live_update=[
        sync('./packages/next', '/app')
    ]
)


docker_build(
    'fp/scout',
    '.',
    only=['./pnpm-lock.yaml', './package.json', './packages/scout'],
    dockerfile='d.scout.dockerfile',
    live_update=[
        sync('./packages/scout', '/app')
    ]
)
k8s_resource(
    workload='kubernetes-ingress-controller-manager',
    links=[
      link(os.getenv('NGROK_URL'), 'Endpoint')
    ],
    labels='ngrok'
)

# k8s_resource(
#     workload='echo-deployment',
#     port_forwards=['8080'],
#     labels='debug'
# )
# k8s_resource(
#     workload='game-2048',
#     port_forwards=['8081:8080'],
#     labels='debug'
# )

k8s_resource(
    workload='next',
    port_forwards=['3000']
)
k8s_resource(
    workload='strapi',
    port_forwards=['1337'],
    links=[
      link('http://localhost:1337/admin', 'Strapi Admin UI')
    ]
)
k8s_resource(
    workload='postgres',
)
k8s_resource(
    workload='pgadmin',
    port_forwards=['5050']
)