load('ext://uibutton', 'cmd_button', 'bool_input', 'location')
load('ext://namespace', 'namespace_create', 'namespace_inject')
namespace_create('drive')

docker_build(
    'localhost:5001/drive-backend:latest',
    context='..',
    dockerfile='../Dockerfile',
    only=['./src/backend', './src/mail', './docker'],
    target = 'backend-production',
    live_update=[
        sync('../src/backend', '/app'),
        run(
            'pip install -r /app/requirements.txt',
            trigger=['./api/requirements.txt']
        )
    ]
)

docker_build(
    'localhost:5001/drive-frontend:latest',
    context='..',
    dockerfile='../src/frontend/Dockerfile',
    only=['./src/frontend', './docker', './.dockerignore'],
    target = 'drive',
    live_update=[
        sync('../src/frontend', '/home/frontend'),
    ]
)

k8s_resource('drive-backend-migrate', resource_deps=['dev-backend-postgres'])
k8s_resource('drive-backend-createsuperuser', resource_deps=['drive-backend-migrate'])
k8s_resource('drive-backend', resource_deps=['drive-backend-migrate', 'dev-backend-redis', 'dev-backend-keycloak', 'dev-backend-postgres', 'dev-backend-minio:statefulset'])
k8s_resource('dev-backend-keycloak', resource_deps=['dev-backend-keycloak-pg'])
k8s_yaml(local('cd ../src/helm && helmfile -n drive -e dev template .'))

migration = '''
set -eu
# get k8s pod name from tilt resource name
POD_NAME="$(tilt get kubernetesdiscovery drive-backend -ojsonpath='{.status.pods[0].name}')"
kubectl -n drive exec "$POD_NAME" -- python manage.py makemigrations
'''
cmd_button('Make migration',
           argv=['sh', '-c', migration],
           resource='drive-backend',
           icon_name='developer_board',
           text='Run makemigration',
)

pod_migrate = '''
set -eu
# get k8s pod name from tilt resource name
POD_NAME="$(tilt get kubernetesdiscovery drive-backend -ojsonpath='{.status.pods[0].name}')"
kubectl -n drive exec "$POD_NAME" -- python manage.py migrate --no-input
'''
cmd_button('Migrate db',
           argv=['sh', '-c', pod_migrate],
           resource='drive-backend',
           icon_name='developer_board',
           text='Run database migration',
)
