name: Publish Demo Server CI

on:
  workflow_run:
    workflows: [ "Docker Image Microservice CI"]
    types:
      - completed
  workflow_dispatch:

env:
  DOCKER_TAG: dev
  STRIPE_TEST_PUBLISH_KEY: '${{ secrets.STRIPE_TEST_PUBLISH_KEY }}'
  STRIPE_TEST_KEY: '${{ secrets.STRIPE_TEST_KEY }}'
  STRIPE_TEST_WEBHOOK_KEY: '${{ secrets.STRIPE_TEST_WEBHOOK_KEY }}'
  STRIPE_TEST_PLAN_PRICE: '${{ secrets.STRIPE_TEST_PLAN_PRICE }}'

jobs:

  build:

    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Publish to demo server
        if: github.repository == 'go-saas/kit'
        uses: appleboy/scp-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD }}
          port: ${{ secrets.PORT }}
          source: "quickstart/,.env,docker-compose.yml,docker-compose.tracing.yml,docker-compose.kafka.yml,docker-compose.ms.yml"
          target: "/app/go-saas-kit"

      - name: Update demo server
        if: github.repository == 'go-saas/kit'
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD }}
          port: ${{ secrets.PORT }}
          envs: DOCKER_TAG,STRIPE_TEST_PUBLISH_KEY,STRIPE_TEST_KEY,STRIPE_TEST_WEBHOOK_KEY,STRIPE_TEST_PLAN_PRICE
          script: |
            echo "$DOCKER_TAG"
            cd /app/go-saas-kit
            cp -r quickstart/demo/. quickstart/configs
            sed -i -e "s/stripe_test_publish_key/$STRIPE_TEST_PUBLISH_KEY/g" quickstart/configs/payment.yaml
            sed -i -e "s/stripe_test_key/$STRIPE_TEST_KEY/g" quickstart/configs/payment.yaml
            sed -i -e "s/stripe_test_webhook_key/$STRIPE_TEST_WEBHOOK_KEY/g" quickstart/configs/payment.yaml
            sed -i -e "s/stripe_test_plan_price/$STRIPE_TEST_PLAN_PRICE/g" quickstart/configs/payment.yaml
            
            sudo docker compose -f docker-compose.yml -f docker-compose.tracing.yml -f docker-compose.kafka.yml -f docker-compose.ms.yml pull
            sudo docker compose -f docker-compose.yml -f docker-compose.tracing.yml -f docker-compose.kafka.yml -f docker-compose.ms.yml up -d --remove-orphans
            sudo docker compose -f docker-compose.yml -f docker-compose.tracing.yml -f docker-compose.kafka.yml -f docker-compose.ms.yml restart
            sudo docker system prune -f
