
stages:     # Define the stages of the pipeline.
  - build
  #- test
  - release

semantic-release:
  image: node:24
  stage: release
  script:
    - apt update && apt install zip -y
    - zip -r dist.zip Web/dist/Web/browser
    - zip -r api.zip Api/build
    - npm install --save-dev @semantic-release/gitlab
    - npx semantic-release --debug
  only:
    - main

docker-build:
  stage: build
  image: docker:latest
  tags:
    - shared
  services:
    - name: docker:dind
      alias: docker
  variables:
    DOCKER_DRIVER: overlay2
    DOCKER_HOST: tcp://docker:2375
    DOCKER_TLS_CERTDIR: ""
  before_script:
    - docker info

    - ip a
  script:
    - 'sed -i "s|\"apiEndpoint\": \"[^\"]*\"|\"apiEndpoint\": \"https\:\/\/""$PUBLIC_WEB_URL""\"|" Web/public/config.json'
    - 'sed -i "s|\"AllowedHosts\": \"[^\"]*\"|\"AllowedHosts\": \"$PUBLIC_WEB_URL\"|" Api/appsettings.json'
    - 'sed -i "s|\"CorsOrigins\": \"[^\"]*\"|\"CorsOrigins\": \"https\:\/\/""$PUBLIC_WEB_URL""\"|" Api/appsettings.json'
    - docker build -t $CI_REGISTRY_IMAGE:latest -t $CI_REGISTRY_IMAGE:${CI_PIPELINE_IID} -f Dockerfile .
    - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY
    - docker push $CI_REGISTRY_IMAGE:latest
    - docker push $CI_REGISTRY_IMAGE:${CI_PIPELINE_IID}
  retry:
    max: 2
    when:
      - runner_system_failure
      - script_failure
      - api_failure

  only:
    - dev
    - main

docker-deploy:
  stage: release
  tags:
    - production
    - shell
  script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY
    - cd deployment
    - docker compose pull
    - docker compose -f docker-compose.yaml up -d
    - docker image prune -f 
  only:
    - dev
    - main

update_db:
  image: mcr.microsoft.com/dotnet/sdk:8.0
  stage: release
  needs: ["docker-deploy"]
  script:
    - cd Api
    - dotnet restore ./Api.csproj
    - dotnet build ./Api.csproj
    - dotnet tool install --global dotnet-ef --version 8.*
    - export PATH="$PATH:/root/.dotnet/tools"
    - dotnet-ef database update --project ./Api.csproj --startup-project ./Api.csproj
  only:
    - dev
    - main
  tags:
    - production
    - docker
  variables:
    ConnectionStrings__DefaultConnection: "Server=localhost;Database=CentrumDb;User=sa;Password=$DB_PASSWORD;TrustServerCertificate=True;"
