name: deploy to production

on: "push"
#    push:
#        branches:
#            - master

jobs:
    deploy:
        name: deploy
        runs-on: ubuntu-latest
        container:
            image: gitbase.de/actions/ubuntu:latest
            volumes:
                - /data:/data
        steps:
            - uses: actions/checkout@v3
              with:
                  fetch-depth: 0
                  lfs: true
                  submodules: true

            - run: |
                  git fetch --force --tags

            # setup node 20
            - name: setup node 20
              uses: actions/setup-node@v3
              with:
                  node-version: 20

            - name: install dependencies
              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
                  sed -i 's#metrictCall = false#metrictCall = true#g' frontend/src/config.ts

                  set -o allexport
                  . ./.env
                  echo "PROJECT_RELEASE=${SENTRY_PROJECT}.r`git rev-list HEAD --count`-`git describe --all --long | sed 's+/+-+'`" >> .env
                  . ./.env
                  set +o allexport
                  echo ______ .env ______
                  cat .env
                  echo
                  sed -i 's#\(const release = \).*#\1"'${PROJECT_RELEASE}'"#g' api/hooks/config-client.js
                  sed -i 's#\(const originURL = \).*#\1"'${LIVE_URL}'"#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

                  test -d api/templates && test -L api/templates/spa.html && rm api/templates/spa.html || test -d api/templates && test -f api/templates/spa.html && rm api/templates/spa.html
                  test -d api/templates && cp frontend/spa.html api/templates/spa.html                  
                  cp frontend/spa.html api/templates/spa.html
                  echo ______ frontend/spa.html ______
                  cat frontend/spa.html

                  sed -i 's#\(PREVIEW_URL=\).*#\1'${LIVE_URL}/preview'#g' api/config.yml.env
                  echo ______ api/config.yml.env ______
                  cat api/config.yml.env

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

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

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

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

            - name: staging
              # only if branch is dev
              if: github.ref == 'refs/heads/dev'
              env:
                  # /data/ORG/PROJECT/BRANCH
                  API_BASEDIR: /data/${{ github.repository }}/${{ github.ref_name }}
                  COMPOSE_PROJECT_NAME: ${{ github.repository }}-${{ github.ref_name }}
              run: |
                  # read .env
                  set -o allexport
                  . ./.env
                  . ./api/config.yml.env
                  set +o allexport

                  # replace / with -
                  COMPOSE_PROJECT_NAME=`echo $COMPOSE_PROJECT_NAME | sed 's+/+-+g'`

                  mkdir -p $API_BASEDIR/frontend
                  rsync -av api $API_BASEDIR/
                  rsync -av frontend/dist $API_BASEDIR/frontend/
                  rsync -av frontend/assets $API_BASEDIR/frontend/
                  sed -i 's#\(PREVIEW_URL=\).*#\1'${STAGING_URL}/preview'#g' $API_BASEDIR/api/config.yml.env

                  docker compose -f docker-compose-staging.yml -p $COMPOSE_PROJECT_NAME up -d --build --remove-orphans

                  reloadUrl=${STAGING_URL}/api/_/admin/reload
                  curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ${ADMIN_TOKEN}" -d '{}' "${reloadUrl}"

                  # clear ssr cache
                  ssrUrl=${STAGING_URL}/api/ssr
                  curl -X POST -H "Content-Type: application/json" -d '{}' "${ssrUrl}?clear=1"

            - name: deploy
              # only if branch is master
              if: github.ref == 'refs/heads/master'
              env:
                  RSYNC_USER: ${{ github.repository }}
                  RSYNC_PASS: ${{ github.token }}
                  BRANCH: ${{ github.ref_name }}
              run: |
                  # read .env
                  set -o allexport
                  . ./.env
                  . ./api/config.yml.env
                  set +o allexport


                  # if RSYNC_USER or RSYNC_KEY is not set, exit
                  if [ -z "${RSYNC_USER}" ]; then
                      echo "RSYNC_USER missing, exiting"
                      exit 1
                  fi
                  if [ -z "${RSYNC_PASS}" ]; then
                      echo "RSYNC_PASS missing, exiting"
                      exit 1
                  fi
                  if [ -z "${RSYNC_HOST}" ]; then
                      echo "RSYNC_HOST missing, exiting"
                      exit 1
                  fi
                  if [ -z "${RSYNC_PORT}" ]; then
                      echo "RSYNC_PORT missing, exiting"
                      exit 1
                  fi

                  echo "Deploying ${BRANCH} to ${RSYNC_HOST} on port ${RSYNC_PORT} as ${RSYNC_USER}"

                  excludes=""
                  if [ "${BRANCH}" = "master" ]; then
                      excludes='--exclude=src --exclude=*.map'
                      echo "master deploy, excluding $excludes"
                  fi

                  SSH_CMD="sshpass -p ${RSYNC_PASS} ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -p ${RSYNC_PORT} -l ${RSYNC_USER}"

                  # sync frontend
                  rsync -rlcgD --perms -i -u -v --stats --progress \
                      --delete \
                      -e "${SSH_CMD}" \
                      $excludes \
                      frontend/ \
                      ${RSYNC_HOST}:./frontend/ \

                  # sync api config
                  rsync -rlcgD --perms -i -u -v --stats --progress \
                      --delete \
                      -e "${SSH_CMD}" \
                      api/ \
                      ${RSYNC_HOST}:./api/

                  # create media directory
                  mkdir media
                  chmod 770 media
                  rsync -rlcgD --perms -i -u -v --stats --progress \
                      -e "${SSH_CMD}" \
                      media \
                      ${RSYNC_HOST}:./


                  reloadUrl=${LIVE_URL}/api/_/admin/reload
                  curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ${ADMIN_TOKEN}" -d '{}' "${reloadUrl}"

                  # clear ssr cache
                  ssrUrl=${LIVE_URL}/api/ssr
                  curl -X POST -H "Content-Type: application/json" -d '{}' "${ssrUrl}?clear=1"
