stages:
  - lint
  - build
  - upload
  - release

lint-job:
  stage: lint
  image:
    name: $CI_REGISTRY/stoplight/spectral:latest
    entrypoint: [ "" ]
  script:
    - spectral lint spec/*.yml

build:
  stage: build
  image: $CI_REGISTRY/node:current-alpine
  before_script:
    - echo 'http://dl-cdn.alpinelinux.org/alpine/edge/community' >> /etc/apk/repositories
    - apk update
    - apk add yq bash
    - yq -V
    - npm install -g @apidevtools/swagger-cli
    - mkdir dist
  script:
    - ./bundle-docs.sh
    - yq e '.info.description.$ref = "../dist/docs.bundled.md"' -i spec/zustelldienst.yml
    - cp metadata-schema/antragsmetadaten.schema.json dist/
    - swagger-cli bundle -t yaml -o dist/zustelldienst.yml spec/zustelldienst.yml
    # - yq e '.components.schemas.Antragsmetadaten.$ref = "./antragsmetadaten.schema.json"' -i dist/zustelldienst.yml
  # find ./spec -type f -name "*.yml" -exec sh -c 'swagger-cli bundle -t yaml -o dist/$(basename {}) {}' \;
  artifacts:
    expose_as: 'Built API spec'
    paths:
      - dist/
    expire_in: 30 days

upload:
  stage: upload
  image: $CI_REGISTRY/alpine:latest
  only:
    refs:
      - tags
    variables:
      - $CI_COMMIT_TAG
  before_script:
    - apk add rsync openssh-client
    - eval $(ssh-agent -s)
    - echo "$CI_DEPLOYMENT_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - echo "$UBERSPACE_KNOWN_HOST" >> ~/.ssh/known_hosts
  script:
    - sed "s,API_VERSION,$CI_COMMIT_TAG/zustelldienst.yml,g" ui/config.js.template > ui/config.js
    - sed -i "s,API_VERSION,$CI_COMMIT_TAG,g" dist/zustelldienst.yml
    - sed -i "s,API_VERSION,$CI_COMMIT_TAG,g" dist/antragsmetadaten.schema.json
    - rsync -rLvz --size-only --checksum -e "ssh -o CheckHostIP=no" --ipv4 --progress ./ui/. fitko@dorado.uberspace.de:html/
    - rsync -rLvz --size-only --checksum -e "ssh -o CheckHostIP=no" --ipv4 --progress ./assets/. fitko@dorado.uberspace.de:html/$CI_COMMIT_TAG/
    - rsync -rLvz --size-only --checksum -e "ssh -o CheckHostIP=no" --ipv4 --progress ./dist/. fitko@dorado.uberspace.de:html/$CI_COMMIT_TAG/

#release-new-api-version:
#  stage: release
#  image: registry.gitlab.com/gitlab-org/release-cli:latest
#  needs:
#    - job: build
#      artifacts: true
#  only:
#    refs:
#      - main
#      - tags
#    variables:
#      - $CI_COMMIT_TAG
#  script:
#    - release-cli -v
#    - echo "Releasing new API version"
#    - release-cli create --name "$CI_COMMIT_TAG" --description './CHANGELOG.md'
#      --tag-name $CI_COMMIT_TAG
#      --assets-link '{"name":"combined-$CI_COMMIT_TAG","url":"https://fitko.uber.space/$CI_COMMIT_TAG/zustelldienst.yml"}'

