name: mesh-net-ci

on:
  push:
    branches: [main]
    paths:
      - "nodes/**"
      - "ansible/**"
      - "bird/**"
      - "wireguard/**"
  pull_request:
    branches: [main]

env:
  AS_NUMBER: "4242421080"
  MESH_DOMAIN: "mesh.riverton.net"
  INVENTORY: "ansible/inventory.yml"

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install network tooling
        run: |
          sudo apt-get update
          sudo apt-get install -y bird2 wireguard-tools yamllint python3-pip
          pip3 install ansible ansible-lint netaddr

      - name: Lint YAML and Ansible
        run: |
          yamllint nodes ansible
          ansible-lint ansible/playbooks

      - name: Validate WireGuard peers
        run: |
          for key in wireguard/peers/*.pub; do
            wg pubkey < /dev/null >/dev/null 2>&1 || true
            test "$(wc -c < "$key")" -ge 44
          done

      - name: Render router configs
        run: |
          ansible-playbook \
            -i "$INVENTORY" \
            ansible/playbooks/render-edge.yml \
            --check \
            --diff

      - name: Validate BIRD configuration
        run: |
          for cfg in build/bird/*.conf; do
            bird -p -c "$cfg"
          done

  deploy:
    needs: validate
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    environment: production
    concurrency:
      group: mesh-router-deploy
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@v4

      - name: Install Ansible
        run: pip3 install ansible netaddr

      - name: Load SSH key
        uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.MESH_DEPLOY_KEY }}

      - name: Deploy edge routers
        run: |
          ansible-playbook \
            -i "$INVENTORY" \
            ansible/playbooks/deploy-edge.yml \
            --limit edge_routers \
            --forks 4

      - name: Reload monitoring targets
        run: |
          ansible-playbook \
            -i "$INVENTORY" \
            ansible/playbooks/reload-monitoring.yml