name: deploy to production

on: "push"
jobs:
    lighthouse-evaluation:
        runs-on: ubuntu-latest
        container:
            image: gitbase.de/actions/ubuntu:latest
            volumes:
                - /data:/data
        services:
            mongo:
                image: mongo:4.2
                ports:
                    - 27017:27017
                options: --name mongo

            maildev:
                image: gitbase.de/robin/maildev:latest
                ports:
                    - 80:80
                    - 25:25
                options: --name maildev

            tibi-server:
                image: gitbase.de/cms/tibi-server
                ports:
                    - 8080:8080
                env:
                    DB_DIAL: mongodb://mongo
                    API_PORT: 8080
                    MAIL_HOST: maildev:25
                    SECURITY_ALLOWABSOLUTEPATHS: "true"
                    SECURITY_ALLOWUPPERPATHS: "true"
                    SECURITY_ALLOWRELATIVEPATHS: "true"
                options: --name tibi-server
                volumes:
                    - ${{ github.workspace }}:/repo

            live-server:
                image: gitbase.de/robin/apache-image:latest
                ports:
                    - 8081:80
                volumes:
                    - ${{ github.workspace }}/frontend:/usr/local/apache2/htdocs/
                options: --name live-server

        steps:
            - uses: actions/checkout@v3
              with:
                  fetch-depth: 0

            - name: setup node 18
              uses: actions/setup-node@v3

            - name: Initialize database
              uses: ./.github/actions/init-db
              with:
                  TIBI_API_NAMESPACE: allkids_erfurt
                  TIBI_API_CONFIG_PATH: /repo/api/config.yml
                  PROJECT_NAME: AllKids

            - name: SERVICE RESTART
              uses: docker://docker
              with:
                  args: docker restart live-server tibi-server mongo maildev

            - name: Cache node modules
              uses: actions/cache@v3
              with:
                  path: |
                      .yarn/cache
                  key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
                  restore-keys: |
                      ${{ runner.os }}-yarn-

            - name: setup yarn
              run: |
                  corepack enable
                  corepack prepare yarn@3.2.4 --activate
                  yarn install

            - name: modify config
              run: |
                  sed -i 's#\(sentryEnvironment.*\)".*"#\1"${GITHUB_REF_NAME}"#g' frontend/src/config.ts
                  sed -i 's#//\( sentry\\.init.*\)#\1#g' frontend/src/config.ts
                  export $(cat .env | xargs)
                  echo "PROJECT_RELEASE=${RELEASE_PROJECT_SLUG}.r`git rev-list HEAD --count`-`git describe --all --long | sed 's+/+-+'`" >> .env
                  export $(cat .env | xargs)
                  echo ______ .env ______
                  cat .env
                  echo
                  sed -i 's#\(const release = \).*#\1"'${PROJECT_RELEASE}'"#g' api/hooks/config-client.js

                  # bash scripts/preload-meta.sh frontend/spa.html
                  # bash scripts/preload-meta.sh frontend/spa.html > frontend/_spa.html
                  # cp frontend/_spa.html frontend/spa.html

                  export stamp=`date +%s`
                  sed -i s/__TIMESTAMP__/$stamp/g frontend/spa.html
                  # sed -i s/__TIMESTAMP__/$stamp/g frontend/serviceworker.js
                  # cat frontend/serviceworker.js
                  # rm api/templates/spa.html
                  # cp frontend/spa.html api/templates/spa.html
                  echo ______ frontend/spa.html ______
                  cat frontend/spa.html

            - name: build
              env:
                  FORCE_COLOR: "true"
              run: |
                  yarn build

            - name: build ssr
              env:
                  FORCE_COLOR: "true"
              run: |
                  yarn build:server

            #- name: Load .env file
            #  run: |
            #    set -a
            #    source .env
            #    set + a

            - name: SERVICE RESTART
              uses: docker://docker
              with:
                  args: docker restart live-server tibi-server

            - name: wait for boot
              run: |
                  sleep 15

            - name: Inspect Service Containers
              run: |
                  for container_id in $(docker ps --format '{{.ID}}'); do
                      echo "::group:: Container logs:"
                      docker logs $container_id || true
                      echo "::endgroup::"
                  done

            #- name: Wait for Live Server
            #  run: |
            #    attempts=0
            #    max_attempts=5
            # same port since its inside the same network, so not 8081....
            #    while ! curl --fail "http://live-server:80"; do
            #    if [ $attempts -eq $max_attempts ]; then
            #           echo "Live server not ready after $max_attempts attempts"
            #           echo "${{ toJson(job) }}"
            #           curl -v "http://live-server:80" || true
            #           echo "::group::liveserver logs"
            #           docker logs live-server
            #           echo "::endgroup::"
            #           echo "::group:: tibi-server logs"
            #             docker logs tibi-server
            #           echo "::endgroup::"
            #           echo "::group:: tibi-server curl"
            #           docker exec live-server cat /var/log/apache2/access.log || true
            #           docker exec live-server bash -c "apt-get update && apt-get install -y curl"
            #           docker exec live-server echo $PATH
            #           docker exec live-server bash -c 'curl -v "http://tibi-server:8080/api/v1/_/allkids_erfurt/ssr?token=owshwerNwoa&url=/noindex"'
            #           echo "::endgroup::"
            #           exit 1
            #     fi
            #     attempts=$((attempts+1))
            #     echo "Waiting for live-server to be ready... attempt $attempts"
            #     sleep 5
            #     done

            - name: Test HTTP Request
              run: |
                  curl -v http://live-server:80

            - name: Install Chrome
              run: |
                  wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
                  sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'

                  sudo apt-get update
                  sudo apt-get install -y google-chrome-stable

            # Lighthouse Analysis Step
            - name: Lighthouse Analysis
              run: |
                  yarn add lighthouse
                  npx lighthouse http://live-server:80 --output json --output-path /tmp/lighthouse-report.json --chrome-flags="--headless --no-sandbox --disable-dev-shm-usage"

            - name: upload-to-nextcloud
              run: |
                  sudo apt-get update && sudo apt-get install -y curl bash findutils
                  export datetime=`date +%Y-%m-%d_%H-%M-%S`
                  mkdir -p /tmp/cloudsend/${GITHUB_REF_NAME}/$${datetime}
                  mv /tmp/lighthouse-report.json /tmp/cloudsend/${GITHUB_REF_NAME}/$${datetime}/
                  ./scripts/cloudsend.sh /tmp/cloudsend/ https://www.basiswolke.de/index.php/s/xHGsypbqiifnGH5

    deploy:
        name: deploy
        runs-on: ubuntu-latest
        container:
            image: gitbase.de/actions/ubuntu:latest
            volumes:
                - /data:/data

        services:
            mongo:
                image: mongo:4.2
                ports:
                    - 27017:27017

            maildev:
                image: gitbase.de/robin/maildev:latest
                ports:
                    - 80:80
                    - 25:25

            tibi-server:
                image: gitbase.de/cms/tibi-server
                ports:
                    - 8080:8080
                env:
                    DB_DIAL: mongodb://mongo
                    API_PORT: 8080
                    MAIL_HOST: maildev:25
                    SECURITY_ALLOWABSOLUTEPATHS: "true"
                    SECURITY_ALLOWUPPERPATHS: "true"
                    SECURITY_ALLOWRELATIVEPATHS: "true"

            live-server:
                image: gitbase.de/robin/live-server:latest
                ports:
                    - 8081:8081

        steps:
            - uses: actions/checkout@v3
              with:
                  fetch-depth: 0

            - name: setup node 18
              uses: actions/setup-node@v3

            - name: install dependencies
              env:
                  FORCE_COLOR: "true"
              run: |
                  npm install -g yarn
                  yarn install

            - name: modify config
              run: |
                  sed -i 's#\(sentryEnvironment.*\)".*"#\1"${GITHUB_REF_NAME}"#g' frontend/src/config.ts
                  sed -i 's#//\( sentry\\.init.*\)#\1#g' frontend/src/config.ts
                  export $(cat .env | xargs)
                  echo "PROJECT_RELEASE=${RELEASE_PROJECT_SLUG}.r`git rev-list HEAD --count`-`git describe --all --long | sed 's+/+-+'`" >> .env
                  export $(cat .env | xargs)
                  echo ______ .env ______
                  cat .env
                  echo
                  sed -i 's#\(const release = \).*#\1"'${PROJECT_RELEASE}'"#g' api/hooks/config-client.js

                  # bash scripts/preload-meta.sh frontend/spa.html
                  # bash scripts/preload-meta.sh frontend/spa.html > frontend/_spa.html
                  # cp frontend/_spa.html frontend/spa.html

                  export stamp=`date +%s`
                  sed -i s/__TIMESTAMP__/$stamp/g frontend/spa.html
                  # sed -i s/__TIMESTAMP__/$stamp/g frontend/serviceworker.js
                  # cat frontend/serviceworker.js
                  # rm api/templates/spa.html
                  # cp frontend/spa.html api/templates/spa.html
                  echo ______ frontend/spa.html ______
                  cat frontend/spa.html

            - name: build
              env:
                  FORCE_COLOR: "true"
              run: |
                  yarn build

            - name: build ssr
              env:
                  FORCE_COLOR: "true"
              run: |
                  yarn build:server

            - name: build legacy
              env:
                  FORCE_COLOR: "true"
              run: |
                  yarn build:legacy

            - name: deploy
              if: github.ref == 'refs/heads/master'
              env:
                  RSYNC_USER: "allkids_rsync_master"
                  RSYNC_PASS: ${{ secrets.rsync_master }}
              run: |
                  scripts/deploy.sh ftp1.webmakers.de $RSYNC_USER $RSYNC_PASS
