#!/usr/bin/env nu
# Invoke cluster operations for this project's rustelo_website component.
# Usage: nu provisioning/deploy.nu <install|update|delete|restart|health> [--workspace-name secrets-base] [--kubeconfig <path>]
# Env: DEV_ROOT, PROVISIONING, LIAN_BUILD_ROOT

def main [
    op: string = "install"
    --kubeconfig: string = ""
    --workspace-name: string = "secrets-base"
]: nothing -> nothing {
    let dev_root     = ($env.DEV_ROOT? | default "/Users/Akasha/Development")
    let prov         = ($env.PROVISIONING? | default $"($dev_root)/project-provisioning/provisioning")
    let lb_root      = ($env.LIAN_BUILD_ROOT? | default $"($dev_root)/lian-build")
    let project_root = ($env.FILE_PWD | path dirname)
    let cluster_dir  = $"($project_root)/provisioning/rustelo_website/cluster"
    let overrides    = $"($project_root)/provisioning/workspaces/($workspace_name).overrides.ncl"
    let catalog_comp = $"($project_root)/provisioning/catalog/component/rustelo_website.ncl"

    if not ($overrides | path exists) {
        error make { msg: $"workspace overrides not found: ($overrides)" }
    }

    let p = (
        ^nickel export
            --import-path $prov
            --import-path $lb_root
            $"($project_root)/provisioning/project.ncl"
            --format json
        | from json
    )
    let ws = (
        ^nickel export
            --import-path $prov
            $overrides
            --format json
        | from json
    )

    # Pull env block from the catalog component when present — these become
    # WEBSITE_ENV_* vars forwarded to the cluster install script.
    let catalog_env = if ($catalog_comp | path exists) {
        (
            ^nickel export
                --import-path $prov
                --import-path $lb_root
                $catalog_comp
                --format json
            | from json
            | get -o env
            | default {}
        )
    } else { {} }

    let env_vars = {
        WEBSITE_NAME:             $p.name
        WEBSITE_NAMESPACE:        $p.namespace
        WEBSITE_IMAGE:            $"($p.image_base):($p.image_tag)"
        WEBSITE_PORT:             ($p.port | into string)
        WEBSITE_DOMAIN:           $p.domain
        WEBSITE_CLUSTER_ISSUER:   $ws.cluster_issuer
        WEBSITE_GATEWAY_NAME:     $ws.gateway_name
        WEBSITE_GATEWAY_NS:       $ws.gateway_ns
        WEBSITE_GATEWAY_FIP:      $ws.gateway_fip
        WEBSITE_REGISTRY_SECRET:  $ws.registry_secret
        WEBSITE_DATA_PVC_ENABLED: ($p.data_pvc.enabled | into string)
        WEBSITE_DATA_MOUNT:       "/var/www"
        # Serialised env block for the cluster script to inject into the Deployment
        WEBSITE_EXTRA_ENV:        ($catalog_env | to json --raw)
    }
    let env_vars = if ($kubeconfig | is-not-empty) { $env_vars | insert KUBECONFIG $kubeconfig } else { $env_vars }

    with-env $env_vars {
        run-external "bash" $"($cluster_dir)/install-rustelo_website.sh" $op
    }
}
