stages:
  - validate
  - build
  - test
  - deploy

variables:
  COMMUNITY_ASN: "64542"
  OPENWRT_VERSION: "23.05.5"
  INVENTORY_FILE: "inventory/mesh-sites.yml"
  CONFIG_OUTPUT_DIR: "build/rendered-configs"

default:
  image: registry.communitymesh.example.net/infra/mesh-ci:2026.07
  before_script:
    - python --version
    - ansible --version

yamllint:
  stage: validate
  script:
    - yamllint inventory playbooks services

ansible_lint:
  stage: validate
  script:
    - ansible-lint playbooks/*.yml

validate_prefixes:
  stage: validate
  script:
    - python tools/validate_prefix_plan.py --asn "$COMMUNITY_ASN" --inventory "$INVENTORY_FILE"
    - python tools/check_overlapping_subnets.py inventory/prefixes.yml

render_node_configs:
  stage: build
  script:
    - mkdir -p "$CONFIG_OUTPUT_DIR"
    - ansible-playbook playbooks/render-node-configs.yml -i "$INVENTORY_FILE"
  artifacts:
    paths:
      - build/rendered-configs/
    expire_in: 14 days

build_gateway_image:
  stage: build
  script:
    - ./tools/build-openwrt-image.sh --version "$OPENWRT_VERSION" --profile x86-64 --features bgp,babel,wireguard
  artifacts:
    paths:
      - build/images/
    expire_in: 14 days

lab_smoke_test:
  stage: test
  needs:
    - render_node_configs
  script:
    - ./tools/lab-up.sh --topology test/lab-topology.yml
    - pytest -q test/smoke --inventory "$INVENTORY_FILE"
  after_script:
    - ./tools/lab-down.sh

deploy_staging_gateways:
  stage: deploy
  environment:
    name: staging
  needs:
    - render_node_configs
    - lab_smoke_test
  script:
    - ansible-playbook playbooks/deploy-gateways.yml -i "$INVENTORY_FILE" --limit staging
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

deploy_production_gateways:
  stage: deploy
  environment:
    name: production
  needs:
    - render_node_configs
    - build_gateway_image
  script:
    - ansible-playbook playbooks/deploy-gateways.yml -i "$INVENTORY_FILE" --limit border_routers --diff
    - ansible-playbook playbooks/reload-routing.yml -i "$INVENTORY_FILE" --limit border_routers
  rules:
    - if: '$CI_COMMIT_TAG =~ /^release-[0-9]{4}\.[0-9]{2}\.[0-9]+$/'
      when: manual
  resource_group: production-routing