# Template Version: Hello-World-Workflow-2025-04-24-v3
# Description: A simple Hello World workflow using SonataFlow and Tekton, integrated with Orchestrator
# Changes:
# - Adjusted GitOps path to ensure SonataFlow CR is in ./app-of-apps for ArgoCD
# - Added sonataflow.org/profile annotation to enable Data Index Service integration
# - Simplified to a minimal Hello World workflow
# - Uses Tekton for CI/CD, based on python.yaml structure
# - Deploys to openshift-serverless-logic via ArgoCD in rhtap namespace
# - Integrates with Orchestrator plug-in via catalog registration
# DEPLOY:
# 1. Ensure GitHub Enterprise integration is configured in app-config-rhdh.yaml
# 2. Ensure Data Index Service route is accessible in sonataflow-infra
# 3. Save as hello-world-workflow.yaml in /templates/
# 4. Set permissions: chmod 644 /templates/hello-world-workflow.yaml
# 5. Reload catalog: curl -X POST http://<rhdh-route>/api/catalog/refresh
# 6. Verify in RHDH UI under Create > Templates and Orchestrator > Workflows

apiVersion: scaffolder.backstage.io/v1beta3
kind: Template
metadata:
  name: hello-world-workflow
  title: Hello World Workflow
  description: A simple Hello World workflow using SonataFlow and Tekton
  annotations:
    backstage.io/techdocs-ref: dir:.
    orchestrator/workflow: hello-world
  tags:
    - orchestrator
    - sonataflow
    - tekton
spec:
  owner: janus-orchestrator
  type: workflow
  parameters:
    - title: Workflow Software Project
      description: Configure the github repository where the workflow is located
      required:
        - orgName
        - repoName
        - workflowId
        - description
        - owner
        - system
      properties:
        orgName:
          title: Organization Name
          type: string
          ui:autofocus: true
          description: Github Enterprise Organization Name
          default: hcs-assets
        repoName:
          title: Repository Name
          type: string
          description: Github repository name
          pattern: '^([a-z][a-z0-9-]*)*$'
          default: hello-world
        description:
          title: Description
          type: string
          description: Description added to the README file
          default: A simple Hello World workflow for OpenShift Serverless Logic
        workflowId:
          title: Workflow ID
          type: string
          pattern: "^([a-z][a-z0-9]*)$"
          description: Unique identifier of the workflow in SonataFlow
          default: hello-world
        owner:
          title: Owner
          type: string
          ui:field: EntityPicker
          ui:options:
            catalogFilter:
              kind:
                - Group
                - User
          default: user:guest
        system:
          title: System
          type: string
          description: The system this workflow belongs to
          ui:field: EntityPicker
          ui:options:
            catalogFilter:
              kind:
                - System
          default: system:default/sonataflow-workflows
    - title: Build Environment
      required:
        - namespace
        - argocdNamespace
      properties:
        namespace:
          title: Workflow Namespace
          type: string
          default: openshift-serverless-logic
          description: Deployment namespace for workflow applications
        argocdNamespace:
          title: GitOps Namespace
          type: string
          default: rhtap
          description: Namespace where ArgoCD is running
  steps:
    # Step 1: Validate inputs
    - id: validate-inputs
      name: Validate Inputs
      action: debug:log
      input:
        message: >
          {% if parameters.workflowId | length < 1 or not (parameters.workflowId matches parameters.workflowId.pattern) %}
            Error: Workflow ID must be lowercase alphanumeric, starting with a letter.
          {% elif not parameters.system %}
            Error: System must be a non-empty string (e.g., system:default/sonataflow-workflows).
          {% elif not parameters.argocdNamespace %}
            Error: GitOps Namespace must be a non-empty string (e.g., rhtap).
          {% else %}
            Validation passed: Workflow ID ${{ parameters.workflowId }}, system ${{ parameters.system }}, and GitOps Namespace ${{ parameters.argocdNamespace }} are valid.
          {% endif %}
      if: >
        {{ parameters.workflowId | length < 1 or not (parameters.workflowId matches parameters.workflowId.pattern) or not parameters.system or not parameters.argocdNamespace }}
      then:
        - action: debug:error
          input:
            message: >
              Invalid inputs: Workflow ID must be lowercase alphanumeric, starting with a letter, system and GitOps Namespace must be non-empty strings.

    # Step 2: Serialize the SonataFlow workflow YAML
    - id: serialize-workflow
      name: Serialize Workflow YAML
      action: roadiehq:utils:serialize:yaml
      input:
        data:
          apiVersion: sonataflow.org/v1alpha08
          kind: SonataFlow
          metadata:
            name: ${{ parameters.workflowId }}
            namespace: ${{ parameters.namespace }}
            annotations:
              sonataflow.org/description: ${{ parameters.description }}
              sonataflow.org/version: 0.0.1
              sonataflow.org/profile: prod
              orchestrator/workflow: ${{ parameters.workflowId }}
          spec:
            flow:
              states:
                - name: HelloWorld
                  type: operation
                  actions:
                    - name: printHello
                      functionRef:
                        refName: greetFunction
                        arguments:
                          message: "Hello World"
                  end: true
              functions:
                - name: greetFunction
                  type: custom
                  operation: sysout
              start: HelloWorld

    # Step 3: Write the workflow YAML to a file in the app-of-apps directory
    - id: generate-workflow
      name: Generate Workflow YAML
      action: roadiehq:utils:fs:write
      input:
        path: gitops/app-of-apps/${{ parameters.workflowId }}.sw.yaml
        content: ${{ steps['serialize-workflow'].output.serialized }}

    # Step 4: Serialize catalog-info.yaml
    - id: serialize-catalog
      name: Serialize Catalog Info
      action: roadiehq:utils:serialize:yaml
      input:
        data:
          apiVersion: backstage.io/v1alpha1
          kind: Component
          metadata:
            name: ${{ parameters.workflowId }}-workflow
            description: ${{ parameters.description }}
            annotations:
              orchestrator/workflow: ${{ parameters.workflowId }}
              github.com/project-slug: ${{ parameters.orgName }}/${{ parameters.repoName }}
          spec:
            type: workflow
            lifecycle: production
            owner: ${{ parameters.owner }}
            system: ${{ parameters.system }}

    # Step 5: Write catalog-info.yaml
    - id: generate-catalog
      name: Generate Catalog Info
      action: roadiehq:utils:fs:write
      input:
        path: workflow/catalog-info.yaml
        content: ${{ steps['serialize-catalog'].output.serialized }}

    # Step 6: Fetch source code skeleton
    - id: fetch-skeleton
      name: Fetch Skeleton
      action: fetch:template
      input:
        url: ../../skeleton/source-repo
        targetPath: workflow
        values:
          name: ${{ parameters.workflowId }}
          namespace: ${{ parameters.namespace }}
          description: ${{ parameters.description }}
          dockerfile: docker/Dockerfile
          buildContext: .
          gitopsSecretName: gitops-auth-secret
          image: rhtap-quay-quay-rhtap-quay.pes-dev-e6615681e74d1ae8dcbb77cfdab239d6-0000.eu-de.containers.appdomain.cloud/${{ parameters.orgName }}/${{ parameters.repoName }}
          tags: '["sonataflow", "workflow", "serverless", "tekton"]'
          repoURL: https://github.ibm.com/${{ parameters.orgName }}/${{ parameters.repoName }}-gitops
          owner: ${{ parameters.orgName }}/hcs-asset-engineering-core-contributors
          repoSlug: ${{ parameters.orgName }}/${{ parameters.repoName }}
          defaultBranch: main
          isTekton: true
          isJenkins: false
          system: ${{ parameters.system }}

    # Step 7: Fetch Tekton CI components
    - id: fetch-ci-skeleton
      name: Fetch CI Components
      action: fetch:template
      input:
        url: ../../skeleton/ci/source-repo/tekton
        targetPath: workflow
        values:
          name: ${{ parameters.workflowId }}
          namespace: ${{ parameters.namespace }}
          description: ${{ parameters.description }}
          dockerfile: docker/Dockerfile
          buildContext: .
          gitopsSecretName: gitops-auth-secret
          image: rhtap-quay-quay-rhtap-quay.pes-dev-e6615681e74d1ae8dcbb77cfdab239d6-0000.eu-de.containers.appdomain.cloud/${{ parameters.orgName }}/${{ parameters.repoName }}
          tags: '["sonataflow", "workflow", "serverless", "tekton"]'
          repoURL: https://github.ibm.com/${{ parameters.orgName }}/${{ parameters.repoName }}-gitops
          owner: ${{ parameters.orgName }}/hcs-asset-engineering-core-contributors
          repoSlug: ${{ parameters.orgName }}/${{ parameters.repoName }}
          defaultBranch: main
          isTekton: true
          isJenkins: false
          system: ${{ parameters.system }}

    # Step 8: Remove any GitHub Actions workflow files
    - id: delete-workflow-files
      name: Delete GitHub Actions Workflow Files
      action: fs:delete
      input:
        files:
          - workflow/.github/workflows/*.yaml
          - workflow/.github/workflows/update_pipelinerun.yaml

    # Step 9: Publish source repository to GitHub
    - id: publish-github
      name: Publish Repository to GitHub
      action: publish:github
      input:
        allowedHosts: ['github.ibm.com']
        description: ${{ parameters.description }}
        repoUrl: github.ibm.com?owner=${{ parameters.orgName }}&repo=${{ parameters.repoName }}
        sourcePath: workflow
        defaultBranch: main
        protectDefaultBranch: false
        allowAutoMerge: true
        deleteBranchOnMerge: true
        repoVisibility: private

    # Step 10: Serialize GitOps catalog-info.yaml
    - id: serialize-gitops-catalog
      name: Serialize GitOps Catalog Info
      action: roadiehq:utils:serialize:yaml
      input:
        data:
          apiVersion: backstage.io/v1alpha1
          kind: Component
          metadata:
            name: ${{ parameters.workflowId }}-gitops
            description: GitOps manifest for ${{ parameters.description }}
            annotations:
              orchestrator/workflow: ${{ parameters.workflowId }}
              github.com/project-slug: ${{ parameters.orgName }}/${{ parameters.repoName }}-gitops
          spec:
            type: gitops
            lifecycle: production
            owner: ${{ parameters.owner }}
            system: ${{ parameters.system }}

    # Step 11: Write GitOps catalog-info.yaml
    - id: generate-gitops-catalog
      name: Generate GitOps Catalog Info
      action: roadiehq:utils:fs:write
      input:
        path: gitops/app-of-apps/catalog-info.yaml
        content: ${{ steps['serialize-gitops-catalog'].output.serialized }}

    # Step 12: Fetch GitOps skeleton
    - id: fetch-gitops-skeleton
      name: Fetch GitOps Skeleton
      action: fetch:template
      input:
        url: ../../skeleton/gitops-template
        targetPath: gitops
        values:
          name: ${{ parameters.workflowId }}
          appName: ${{ parameters.repoName }}-gitops
          description: GitOps manifest for ${{ parameters.workflowId }}
          namespace: ${{ parameters.namespace }}
          rhtapNamespace: rhtap
          defaultDeployNamespace: ${{ parameters.namespace }}
          repoURL: https://github.ibm.com/${{ parameters.orgName }}/${{ parameters.repoName }}-gitops
          srcRepoURL: https://github.ibm.com/${{ parameters.orgName }}/${{ parameters.repoName }}
          argoComponent: ./components/${{ parameters.workflowId }}/overlays/development
          argoComponentOverlays: ./components/${{ parameters.workflowId }}/overlays
          owner: ${{ parameters.orgName }}/hcs-asset-engineering-core-contributors
          image: quay.io/redhat-appstudio/dance-bootstrap-app:latest
          srcImage: rhtap-quay-quay-rhtap-quay.pes-dev-e6615681e74d1ae8dcbb77cfdab239d6-0000.eu-de.containers.appdomain.cloud/${{ parameters.orgName }}/${{ parameters.repoName }}
          port: 8080
          argoNS: rhtap
          argoProject: default
          secretRef: gitops-auth-secret
          isTekton: true
          isJenkins: false
          gitSecret: gitops-auth-secret
          gitSecretKey: password
          webhookSecret: pipelines-secret
          webhookSecretKey: webhook.secret
          defaultBranch: main

    # Step 13: Fetch Tekton GitOps CI components
    - id: fetch-gitops-ci-skeleton
      name: Fetch GitOps CI Components
      action: fetch:template
      input:
        url: ../../skeleton/ci/gitops-template/tekton
        targetPath: gitops
        values:
          name: ${{ parameters.workflowId }}
          appName: ${{ parameters.repoName }}-gitops
          description: GitOps manifest for ${{ parameters.workflowId }}
          namespace: ${{ parameters.namespace }}
          rhtapNamespace: rhtap
          defaultDeployNamespace: ${{ parameters.namespace }}
          repoURL: https://github.ibm.com/${{ parameters.orgName }}/${{ parameters.repoName }}-gitops
          srcRepoURL: https://github.ibm.com/${{ parameters.orgName }}/${{ parameters.repoName }}
          argoComponent: ./components/${{ parameters.workflowId }}/overlays/development
          argoComponentOverlays: ./components/${{ parameters.workflowId }}/overlays
          owner: ${{ parameters.orgName }}/hcs-asset-engineering-core-contributors
          image: quay.io/redhat-appstudio/dance-bootstrap-app:latest
          srcImage: rhtap-quay-quay-rhtap-quay.pes-dev-e6615681e74d1ae8dcbb77cfdab239d6-0000.eu-de.containers.appdomain.cloud/${{ parameters.orgName }}/${{ parameters.repoName }}
          port: 8080
          argoNS: rhtap
          argoProject: default
          secretRef: gitops-auth-secret
          isTekton: true
          isJenkins: false
          gitSecret: gitops-auth-secret
          gitSecretKey: password
          webhookSecret: pipelines-secret
          webhookSecretKey: webhook.secret
          defaultBranch: main

    # Step 14: Rename component directory
    - id: renameComponentDir
      name: Rename Component Directory
      action: fs:rename
      input:
        files:
          - from: gitops/components/http
            to: gitops/components/${{ parameters.workflowId }}
            overwrite: true

    # Step 15: Publish GitOps repository to GitHub
    - id: publish-github-gitops
      name: Publish GitOps Repository to Github
      action: publish:github
      input:
        sourcePath: gitops
        allowedHosts: ['github.ibm.com']
        description: GitOps manifest for ${{ parameters.workflowId }}
        repoUrl: github.ibm.com?owner=${{ parameters.orgName }}&repo=${{ parameters.repoName }}-gitops
        defaultBranch: main
        protectDefaultBranch: false
        allowAutoMerge: true
        deleteBranchOnMerge: true
        repoVisibility: private

    # Step 16: Wait for repository availability
    - id: wait-for-github-repository
      name: Waiting for repository availability
      action: debug:wait
      input:
        seconds: 3

    # Step 17: Register workflow in catalog
    - id: register
      name: Register Workflow
      action: catalog:register
      input:
        repoContentsUrl: ${{ steps['publish-github'].output.repoContentsUrl }}
        catalogInfoPath: /catalog-info.yaml

    # Step 18: Register GitOps in catalog
    - id: register-gitops
      name: Register GitOps
      action: catalog:register
      input:
        repoContentsUrl: ${{ steps['publish-github-gitops'].output.repoContentsUrl }}
        catalogInfoPath: /app-of-apps/catalog-info.yaml

    # Step 19: Create ArgoCD resources
    - id: create-argocd-resources
      name: Create ArgoCD Resources
      action: argocd:create-resources
      input:
        appName: ${{ parameters.workflowId }}-app-of-apps
        argoInstance: default
        namespace: rhtap
        repoUrl: https://github.ibm.com/${{ parameters.orgName }}/${{ parameters.repoName }}-gitops.git
        path: ./app-of-apps

  output:
    links:
      - title: Open Workflow in Catalog
        icon: catalog
        entityRef: ${{ steps['register'].output.entityRef }}
      - title: Open GitOps Repository
        icon: github
        url: https://github.ibm.com/${{ parameters.orgName }}/${{ parameters.repoName }}-gitops
      - title: Orchestrator Workflow
        icon: workflow
        url: /orchestrator/workflows/${{ parameters.workflowId }}