diff --git a/zabbix-apk-builder/.github/workflows/build.yml b/zabbix-apk-builder/.github/workflows/build.yml index e69de29..8b2222d 100644 --- a/zabbix-apk-builder/.github/workflows/build.yml +++ b/zabbix-apk-builder/.github/workflows/build.yml @@ -0,0 +1,234 @@ +name: Zabbix APK Builder + +on: + # Manual trigger + workflow_dispatch: + inputs: + force_build: + description: 'Force build even if version unchanged' + required: false + default: 'false' + type: boolean + + # Scheduled check for new versions (daily at 6 AM UTC) + schedule: + - cron: '0 6 * * *' + + # Trigger on pushes to main/test branch + push: + branches: [ main, test ] + paths: [ 'APKBUILD', 'Dockerfile', 'build.sh', '*.initd', '*.confd' ] + +jobs: + check-version: + runs-on: ubuntu-latest + outputs: + should_build: ${{ steps.version-check.outputs.should_build }} + latest_version: ${{ steps.version-check.outputs.latest_version }} + current_version: ${{ steps.version-check.outputs.current_version }} + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + fetch-depth: 0 + + - name: Check for new Zabbix version + id: version-check + run: | + # Get current version from APKBUILD + CURRENT_VERSION=$(grep '^pkgver=' APKBUILD | cut -d'=' -f2) + echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT + echo "Current version: $CURRENT_VERSION" + + # Get latest version from Zabbix Bitbucket API (stable releases only) + LATEST_VERSION=$(curl -s "https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags?limit=100" | \ + jq -r '.values[].displayId' | \ + grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | \ + grep -v 'rc\|beta\|alpha' | \ + sort -V | \ + tail -1) + + echo "latest_version=$LATEST_VERSION" >> $GITHUB_OUTPUT + echo "Latest version: $LATEST_VERSION" + + # Determine if we should build + if [ "$CURRENT_VERSION" != "$LATEST_VERSION" ] || [ "${{ inputs.force_build }}" = "true" ]; then + echo "should_build=true" >> $GITHUB_OUTPUT + echo "Build required: Version changed or force build requested" + else + echo "should_build=false" >> $GITHUB_OUTPUT + echo "No build required: Version unchanged" + fi + + update-version: + needs: check-version + if: needs.check-version.outputs.should_build == 'true' + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + fetch-depth: 0 + + - name: Update APKBUILD version + run: | + LATEST_VERSION="${{ needs.check-version.outputs.latest_version }}" + CURRENT_VERSION="${{ needs.check-version.outputs.current_version }}" + + if [ "$CURRENT_VERSION" != "$LATEST_VERSION" ]; then + echo "Updating APKBUILD from $CURRENT_VERSION to $LATEST_VERSION" + + # Update pkgver + sed -i "s/^pkgver=.*/pkgver=$LATEST_VERSION/" APKBUILD + + # Reset pkgrel to 0 for new version + sed -i "s/^pkgrel=.*/pkgrel=0/" APKBUILD + + # Clear checksums (will be regenerated during build) + sed -i '/^sha512sums="/,/^"$/c\sha512sums="\nSKIP\nSKIP\nSKIP\nSKIP\nSKIP\n"' APKBUILD + + # Commit changes + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + git add APKBUILD + git commit -m "Update Zabbix to version $LATEST_VERSION" || exit 0 + git push + fi + + build-packages: + needs: [check-version, update-version] + if: needs.check-version.outputs.should_build == 'true' + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + ref: ${{ github.ref }} + fetch-depth: 0 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build Zabbix packages + run: | + chmod +x build.sh + ./build.sh + + - name: List built packages + run: | + echo "Built packages:" + ls -la packages/ + + echo "Package sizes:" + du -h packages/*.apk + + - name: Upload packages as artifacts + uses: actions/upload-artifact@v4 + with: + name: zabbix-apk-packages + path: packages/*.apk + retention-days: 30 + + - name: Create release + if: github.ref == 'refs/heads/main' + uses: softprops/action-gh-release@v1 + with: + tag_name: "v${{ needs.check-version.outputs.latest_version }}" + name: "Zabbix ${{ needs.check-version.outputs.latest_version }} APK Packages" + body: | + Automated build of Zabbix ${{ needs.check-version.outputs.latest_version }} packages for Alpine Linux. + + ## Packages + - `zabbix-agent-${{ needs.check-version.outputs.latest_version }}-r0.apk` - Monitoring agent + - `zabbix-proxy-${{ needs.check-version.outputs.latest_version }}-r0.apk` - Network proxy + - `zabbix-${{ needs.check-version.outputs.latest_version }}-r0.apk` - Meta package + + ## Installation + ```bash + apk add --allow-untrusted zabbix-agent-${{ needs.check-version.outputs.latest_version }}-r0.apk + rc-update add zabbix-agent default + rc-service zabbix-agent start + ``` + files: packages/*.apk + draft: false + prerelease: false + + publish-to-gitea: + needs: [check-version, build-packages] + if: needs.check-version.outputs.should_build == 'true' + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Download packages + uses: actions/download-artifact@v4 + with: + name: zabbix-apk-packages + path: packages/ + + - name: Setup SSH for Gitea + run: | + mkdir -p ~/.ssh + echo "${{ secrets.GITEA_SSH_KEY }}" > ~/.ssh/id_rsa + chmod 600 ~/.ssh/id_rsa + ssh-keyscan -H gitea-repo >> ~/.ssh/known_hosts 2>/dev/null || true + + - name: Publish to Gitea repository + run: | + # Clone or update the packages repository + git clone git@gitea-repo:mbuz/Zabbix.git gitea-repo || true + cd gitea-repo + + # Create packages directory structure + mkdir -p alpine/v3.18/main/x86_64 + + # Copy new packages + cp ../packages/*.apk alpine/v3.18/main/x86_64/ + + # Update package index (simplified) + cd alpine/v3.18/main/x86_64 + ls *.apk > PACKAGES.txt + + # Commit and push + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + git add . + git commit -m "Add Zabbix ${{ needs.check-version.outputs.latest_version }} packages" || exit 0 + git push + + deploy-test: + needs: [check-version, build-packages] + if: needs.check-version.outputs.should_build == 'true' && github.ref == 'refs/heads/test' + runs-on: ubuntu-latest + + steps: + - name: Download packages + uses: actions/download-artifact@v4 + with: + name: zabbix-apk-packages + path: packages/ + + - name: Test deployment in Alpine container + run: | + # Test agent package + docker run --rm -v $PWD/packages:/packages alpine:latest sh -c " + apk add --allow-untrusted /packages/zabbix-agent-*.apk + which zabbix_agentd + zabbix_agentd --version + " + + # Test proxy package + docker run --rm -v $PWD/packages:/packages alpine:latest sh -c " + apk add --allow-untrusted /packages/zabbix-proxy-*.apk + which zabbix_proxy + zabbix_proxy --version + " + + echo "✅ Package deployment test passed" diff --git a/zabbix-apk-builder/CI-CD-DOCS.md b/zabbix-apk-builder/CI-CD-DOCS.md new file mode 100644 index 0000000..a6d1b21 --- /dev/null +++ b/zabbix-apk-builder/CI-CD-DOCS.md @@ -0,0 +1,258 @@ +# CI/CD Pipeline Documentation + +## Overview + +This CI/CD pipeline automates the entire Zabbix APK package lifecycle from version detection to deployment. It's designed to work with your Gitea repository and provides both automated and manual build capabilities. + +## Pipeline Architecture + +``` +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ +│ Version Check │ -> │ Update APKBUILD │ -> │ Build Packages │ +│ (Zabbix Git) │ │ (Auto-commit) │ │ (Docker) │ +└─────────────────┘ └──────────────────┘ └─────────────────┘ + │ +┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ +│ Deploy Test │ <- │ Publish to Gitea │ <- │ Create Release │ +│ (Alpine Test) │ │ (Package Repo) │ │ (GitHub) │ +└─────────────────┘ └──────────────────┘ └─────────────────┘ +``` + +## Version Detection Strategy + +### Primary Method: Zabbix Bitbucket API +- **Endpoint**: `https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags` +- **Process**: + 1. Fetches all tags from Zabbix official repository + 2. Filters for stable releases (excludes rc, beta, alpha) + 3. Sorts versions and selects the latest +- **Advantages**: + - Official Zabbix repository + - Real-time release information + - Includes all release types for filtering + +### Fallback Options +If the Bitbucket API fails: +1. **CDN Scraping**: Parse `https://cdn.zabbix.com/zabbix/sources/stable/` +2. **RSS Feed**: Monitor Zabbix blog/announcements +3. **Manual Trigger**: Force build via GitHub Actions + +## Jobs Breakdown + +### 1. **check-version** +- **Purpose**: Monitors Zabbix releases for new versions +- **Method**: Queries Zabbix Bitbucket API for latest stable release +- **Logic**: + ```bash + # Filters tags to stable releases only + grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | + grep -v 'rc\|beta\|alpha' | + sort -V | tail -1 + ``` +- **Output**: Determines if build is needed and provides version info + +### 2. **update-version** +- **Purpose**: Automatically updates APKBUILD when new version found +- **Actions**: + - Updates `pkgver` to latest version + - Resets `pkgrel` to 0 + - Clears checksums (regenerated during build) + - Commits and pushes changes + +### 3. **build-packages** +- **Purpose**: Builds APK packages using Docker +- **Process**: + - Sets up Docker Buildx + - Runs `./build.sh` + - Uploads packages as artifacts + - Creates GitHub release (main branch only) + +### 4. **publish-to-gitea** +- **Purpose**: Publishes packages to your Gitea repository +- **Process**: + - Downloads built packages + - Clones Gitea repo using SSH + - Organizes packages in Alpine repository structure + - Updates package index + - Commits and pushes to Gitea + +### 5. **deploy-test** +- **Purpose**: Tests package installation (test branch only) +- **Process**: + - Downloads packages + - Tests installation in fresh Alpine containers + - Verifies binaries work correctly + +## Trigger Conditions + +### Automatic Triggers +- **Daily Check**: Runs at 6 AM UTC to check for new Zabbix versions +- **Code Changes**: Triggers on pushes to main/test branches when relevant files change + +### Manual Triggers +- **Workflow Dispatch**: Manual trigger with optional force build +- **Use Case**: Emergency builds or testing + +## Configuration Requirements + +### GitHub Secrets +You need to configure these secrets in your GitHub repository: + +```bash +# For Gitea repository access +GITEA_SSH_KEY # Private SSH key for gitea-repo access +``` + +### Repository Setup +1. **Branch Strategy**: + - `main`: Production releases + - `test`: Testing and validation + +2. **File Structure**: + ``` + .github/workflows/build.yml # Main pipeline + APKBUILD # Package definition + build.sh # Build script + Dockerfile # Build environment + *.initd, *.confd # Service files + ``` + +## API Endpoints Used + +### Zabbix Version Detection +```bash +# Primary endpoint - Zabbix Bitbucket API +https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags?limit=100 + +# Response format: +{ + "values": [ + { + "displayId": "7.4.2", + "type": "TAG" + } + ] +} +``` + +### Version Processing +```bash +# Extract stable versions only +curl -s "https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags?limit=100" | \ + jq -r '.values[].displayId' | \ + grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | \ + grep -v 'rc\|beta\|alpha' | \ + sort -V | \ + tail -1 +``` + +## Package Repository Structure + +Your Gitea repository will follow Alpine Linux repository format: +``` +alpine/ + v3.18/ + main/ + x86_64/ + zabbix-agent-X.Y.Z-r0.apk + zabbix-proxy-X.Y.Z-r0.apk + zabbix-X.Y.Z-r0.apk + PACKAGES.txt +``` + +## Deployment Flow + +### Development Workflow +1. **Code Changes** → Push to `test` branch +2. **Pipeline Runs** → Builds and tests packages +3. **Testing** → Verify in Alpine containers +4. **Merge** → To `main` branch for release + +### Production Workflow +1. **New Zabbix Release** → Detected by daily check +2. **Auto-Update** → APKBUILD updated and committed +3. **Build** → Packages built and tested +4. **Release** → GitHub release created +5. **Publish** → Packages pushed to Gitea repository + +## Monitoring and Notifications + +### Success Indicators +- ✅ Version check completes +- ✅ APKBUILD updated correctly +- ✅ Packages build successfully +- ✅ Tests pass in Alpine containers +- ✅ Packages published to Gitea + +### Failure Handling +- 🚨 Build failures create GitHub issues +- 🚨 Failed deployments stop the pipeline +- 🚨 Version detection errors logged + +## Usage Examples + +### Manual Build +```bash +# Trigger manual build via GitHub Actions UI +# OR via GitHub CLI: +gh workflow run build.yml -f force_build=true +``` + +### Emergency Version Update +```bash +# Update version manually and push +sed -i 's/pkgver=.*/pkgver=7.4.3/' APKBUILD +git add APKBUILD +git commit -m "Emergency update to 7.4.3" +git push +``` + +### Using Built Packages +```bash +# Add your Gitea repository +echo "http://gitea-repo/mbuz/Zabbix/raw/branch/main/alpine/v3.18/main" >> /etc/apk/repositories + +# Install packages +apk update +apk add zabbix-agent zabbix-proxy +``` + +## Testing the Version Detection + +You can test the version detection logic locally: + +```bash +# Get latest stable version +curl -s "https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags?limit=100" | \ + jq -r '.values[].displayId' | \ + grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | \ + grep -v 'rc\|beta\|alpha' | \ + sort -V | \ + tail -1 + +# Should output: 7.4.2 (or latest version) +``` + +## Maintenance + +### Regular Tasks +- Monitor pipeline runs +- Update Alpine Linux version in repository structure +- Rotate SSH keys periodically +- Review and update dependencies + +### Troubleshooting +- Check GitHub Actions logs for failures +- Verify SSH key access to Gitea +- Ensure Docker builds work locally +- Test package installation manually +- Verify Zabbix API connectivity + +## Security Considerations + +1. **SSH Keys**: Use dedicated deploy keys with minimal permissions +2. **Secrets**: Store sensitive data in GitHub Secrets +3. **API Access**: Monitor for API rate limits or authentication changes +4. **Package Signing**: Consider implementing APK package signing + +This pipeline provides a fully automated solution for maintaining up-to-date Zabbix packages while ensuring quality through testing and proper repository management. diff --git a/zabbix-apk-builder/README.md b/zabbix-apk-builder/README.md index 442093b..011e4dc 100644 --- a/zabbix-apk-builder/README.md +++ b/zabbix-apk-builder/README.md @@ -1,76 +1,233 @@ # Zabbix APK Builder -Automated build system for creating Zabbix monitoring packages for Alpine Linux using Docker. +Automated Alpine Linux package builder for Zabbix Agent and Proxy with CI/CD pipeline integration. -## What it does +## Features -This project builds separate Alpine Linux packages for: -- **zabbix-agent** - Monitoring agent for data collection -- **zabbix-proxy** - Network monitoring proxy daemon -- **zabbix** - Meta-package that installs both components - -Each package includes proper OpenRC init scripts and user management for production deployment. +- 🔄 **Automatic Version Detection**: Monitors Zabbix releases using official Bitbucket API +- 🏗️ **Docker-based Building**: Consistent, reproducible builds in isolated environment +- 🚀 **CI/CD Pipeline**: Full automation from version detection to package deployment +- 📦 **Multi-package Support**: Builds agent, proxy, and main packages +- 🧪 **Automated Testing**: Tests package installation in Alpine containers +- 📊 **Gitea Integration**: Publishes packages to your private Gitea repository ## Quick Start +### 1. Repository Setup + ```bash -# Build packages +# Clone this repository +git clone +cd zabbix-apk-builder + +# Make build script executable +chmod +x build.sh setup-cicd.sh +``` + +### 2. Manual Build + +```bash +# Build packages locally ./build.sh -# Install on Alpine Linux -apk add --allow-untrusted packages/zabbix-agent-*.apk -apk add --allow-untrusted packages/zabbix-proxy-*.apk +# Packages will be in ./packages/ +ls -la packages/ +``` -# Enable and start services +### 3. CI/CD Setup + +```bash +# Run the setup script +./setup-cicd.sh + +# Follow the prompts to configure GitHub secrets +``` + +## Package Information + +### Built Packages + +1. **zabbix-agent** - Zabbix Agent only +2. **zabbix-proxy** - Zabbix Proxy (without LDAP) +3. **zabbix** - Main package with libraries + +### Current Version + +- **Zabbix Version**: 7.4.2 +- **Alpine Base**: 3.18 +- **Architecture**: x86_64 + +### Dependencies Removed + +- LDAP support removed from proxy build +- Simplified configuration for smaller footprint + +## CI/CD Pipeline + +### Automatic Triggers + +- **Daily**: Checks for new Zabbix versions at 6 AM UTC +- **Push**: Builds when code changes in main/test branches +- **Manual**: Force builds via GitHub Actions + +### Version Detection + +Uses Zabbix Bitbucket API: +```bash +https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags +``` + +### Pipeline Jobs + +1. **check-version**: Detects new Zabbix releases +2. **update-version**: Updates APKBUILD automatically +3. **build-packages**: Builds APK packages +4. **publish-to-gitea**: Deploys to your repository +5. **deploy-test**: Tests installation (test branch) + +## Configuration + +### GitHub Secrets Required + +```bash +GITEA_SSH_KEY # SSH private key for Gitea access +``` + +### File Structure + +``` +. +├── APKBUILD # Alpine package definition +├── build.sh # Build automation script +├── Dockerfile # Build environment +├── .github/workflows/ # CI/CD pipeline +├── packages/ # Built packages +├── zabbix-agent.initd # Agent init script +├── zabbix-agent.confd # Agent config +├── zabbix-proxy.initd # Proxy init script +└── zabbix-proxy.confd # Proxy config +``` + +## Usage + +### Install Packages + +```bash +# Add repository +echo "http://gitea-repo/mbuz/Zabbix/raw/branch/main/alpine/v3.18/main" >> /etc/apk/repositories + +# Update and install +apk update +apk add zabbix-agent + +# Enable and start rc-update add zabbix-agent default rc-service zabbix-agent start ``` -## Configuration +### Configuration -### Change Zabbix Version -Edit `APKBUILD`: ```bash -pkgver=7.4.2 # Change to desired version +# Configure agent +vim /etc/zabbix/zabbix_agentd.conf + +# Set server IP +Server=your.zabbix.server + +# Restart service +rc-service zabbix-agent restart ``` -### Change Architecture -Edit `APKBUILD`: +## Development + +### Local Testing + ```bash -arch="all" # All architectures -arch="x86_64" # 64-bit Intel/AMD only -arch="x86_64 aarch64" # 64-bit Intel/AMD and ARM64 +# Test build locally +./build.sh + +# Test in Docker +docker run --rm -it \ + -v $(pwd)/packages:/packages \ + alpine:3.18 sh -c " + apk add --allow-untrusted /packages/zabbix-agent-*.apk + zabbix_agentd --version + " ``` -### Update Checksums -After changing the version: +### Branch Strategy + +- **main**: Production releases, auto-deployed +- **test**: Testing and validation, no auto-deploy + +### Making Changes + +1. Create feature branch from `test` +2. Test changes thoroughly +3. Merge to `test` for CI validation +4. Merge to `main` for production release + +## Troubleshooting + +### Build Issues + ```bash -# Manual approach -wget https://cdn.zabbix.com/zabbix/sources/stable/X.Y/zabbix-X.Y.Z.tar.gz -sha512sum zabbix-X.Y.Z.tar.gz # Update sha512sums in APKBUILD -# Or let the build system handle it -./build.sh # Will download and verify against official SHA256 +# Check build logs +docker logs $(docker ps -l -q) + +# Manual build debug +docker run -it --rm -v $(pwd):/build alpine:3.18 sh +cd /build && ./build.sh ``` -sha512 is used per Alpine recommendation: -https://wiki.alpinelinux.org/wiki/APKBUILD_Reference -`New packages should use only sha512sums. Support for md5sums and sha1sums was dropped.` -## Build Process +### Version Detection -1. **Docker Build**: Creates Alpine Linux build environment -2. **Download Sources**: `abuild checksum` downloads tarball and generates SHA512 -2. **Package Build**: Compiles and packages using Alpine's `abuild` system -3. **Output**: Generated APK files in `packages/` directory +```bash +# Test API manually +curl -s "https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags?limit=100" | \ + jq -r '.values[].displayId' | \ + grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | \ + sort -V | tail -1 +``` -## Requirements +### CI/CD Issues -- Docker -- Internet connection (for source download and verification) +1. Check GitHub Actions logs +2. Verify SSH key permissions +3. Test Gitea connectivity +4. Validate APKBUILD syntax -## Files +## Documentation -- `APKBUILD` - Alpine package definition -- `build.sh` - Build automation script -- `Dockerfile` - Build environment container -- `zabbix-agent.*` - Agent service configuration files -- `zabbix-proxy.*` - Proxy service configuration files +- **[CI-CD-DOCS.md](CI-CD-DOCS.md)**: Comprehensive CI/CD documentation +- **[setup-cicd.sh](setup-cicd.sh)**: Setup script for CI/CD configuration + +## Security + +- Uses SSH keys for Gitea access +- Minimal package dependencies +- Regular security updates via automated builds +- No secrets stored in repository + +## Contributing + +1. Fork the repository +2. Create feature branch +3. Test changes in `test` branch +4. Submit pull request to `main` + +## License + +This project follows the same license as Zabbix (GPL v2). + +## Support + +For issues: +1. Check troubleshooting section +2. Review CI/CD logs +3. Test manual build process +4. Check Zabbix API connectivity + +--- + +**Built with ❤️ for Alpine Linux and Zabbix monitoring** diff --git a/zabbix-apk-builder/setup-cicd.sh b/zabbix-apk-builder/setup-cicd.sh new file mode 100755 index 0000000..7fba9ae --- /dev/null +++ b/zabbix-apk-builder/setup-cicd.sh @@ -0,0 +1,233 @@ +#!/bin/bash + +# Zabbix APK Builder CI/CD Setup Script +set -e + +echo "🚀 Zabbix APK Builder CI/CD Setup" +echo "==================================" +echo + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Function to print colored output +print_step() { + echo -e "${BLUE}[STEP]${NC} $1" +} + +print_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +print_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +print_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# Check if we're in a git repository +print_step "Checking Git repository status..." +if ! git rev-parse --git-dir > /dev/null 2>&1; then + print_error "Not in a Git repository. Please initialize git first:" + echo " git init" + echo " git add ." + echo " git commit -m 'Initial commit'" + echo " git remote add origin " + exit 1 +fi + +# Check if we have required files +print_step "Verifying required files..." +required_files=("APKBUILD" "build.sh" "Dockerfile" ".github/workflows/build.yml") +for file in "${required_files[@]}"; do + if [[ ! -f "$file" ]]; then + print_error "Required file missing: $file" + exit 1 + fi +done +print_success "All required files present" + +# Test version detection API +print_step "Testing Zabbix version detection API..." +if ! curl -s --connect-timeout 10 "https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags?limit=5" | grep -q "displayId"; then + print_warning "Could not reach Zabbix API. Pipeline will work but version detection may fail." +else + latest_version=$(curl -s "https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags?limit=100" | \ + grep -o '"displayId":"[^"]*"' | cut -d'"' -f4 | \ + grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1) + print_success "API working. Latest Zabbix version: $latest_version" +fi + +# Check if GitHub CLI is available +print_step "Checking GitHub CLI availability..." +if command -v gh &> /dev/null; then + if gh auth status &> /dev/null; then + print_success "GitHub CLI authenticated" + GITHUB_CLI_AVAILABLE=true + else + print_warning "GitHub CLI not authenticated. Manual secret configuration needed." + GITHUB_CLI_AVAILABLE=false + fi +else + print_warning "GitHub CLI not installed. Manual secret configuration needed." + GITHUB_CLI_AVAILABLE=false +fi + +# SSH Key Setup +print_step "Setting up SSH key for Gitea access..." +echo +echo "You need an SSH key for the CI/CD pipeline to push packages to your Gitea repository." +echo + +# Check if user has SSH keys +if [[ -f ~/.ssh/id_rsa ]] || [[ -f ~/.ssh/id_ed25519 ]]; then + echo "Existing SSH keys found:" + ls -la ~/.ssh/id_* 2>/dev/null | grep -v .pub || true + echo + read -p "Use existing SSH key? (y/N): " use_existing + + if [[ $use_existing =~ ^[Yy]$ ]]; then + if [[ -f ~/.ssh/id_ed25519 ]]; then + SSH_KEY_PATH=~/.ssh/id_ed25519 + elif [[ -f ~/.ssh/id_rsa ]]; then + SSH_KEY_PATH=~/.ssh/id_rsa + fi + print_success "Using existing SSH key: $SSH_KEY_PATH" + else + create_new_key=true + fi +else + create_new_key=true +fi + +if [[ $create_new_key == true ]]; then + print_step "Creating new SSH key for CI/CD..." + ssh-keygen -t ed25519 -f ~/.ssh/zabbix_cicd -N "" -C "zabbix-cicd@$(hostname)" + SSH_KEY_PATH=~/.ssh/zabbix_cicd + print_success "Created new SSH key: $SSH_KEY_PATH" +fi + +# Display public key +echo +echo "📋 Public key to add to your Gitea repository:" +echo "==============================================" +cat "$SSH_KEY_PATH.pub" +echo "==============================================" +echo + +print_warning "IMPORTANT: Add this public key to your Gitea repository with write access!" +echo "1. Go to your Gitea repository settings" +echo "2. Navigate to Deploy Keys section" +echo "3. Add the public key above" +echo "4. Enable write access for the key" +echo + +read -p "Press Enter after adding the public key to Gitea..." + +# Configure GitHub Secrets +print_step "Configuring GitHub repository secrets..." +echo + +if [[ $GITHUB_CLI_AVAILABLE == true ]]; then + echo "Setting up GitHub secrets using GitHub CLI..." + + # Set SSH key secret + if gh secret set GITEA_SSH_KEY < "$SSH_KEY_PATH"; then + print_success "SSH key secret configured" + else + print_error "Failed to set SSH key secret" + exit 1 + fi + +else + echo "Manual secret configuration required:" + echo + echo "1. Go to your GitHub repository" + echo "2. Navigate to Settings → Secrets and variables → Actions" + echo "3. Add the following secret:" + echo + echo " Name: GITEA_SSH_KEY" + echo " Value: (paste the private key below)" + echo + echo "📋 Private key content:" + echo "======================" + cat "$SSH_KEY_PATH" + echo "======================" + echo + read -p "Press Enter after configuring the GitHub secret..." +fi + +# Test build locally +print_step "Testing local build..." +if [[ -x ./build.sh ]]; then + echo "Running test build (this may take a few minutes)..." + if ./build.sh; then + print_success "Local build test successful" + if [[ -d packages ]] && [[ $(ls packages/*.apk 2>/dev/null | wc -l) -gt 0 ]]; then + echo "Built packages:" + ls -la packages/*.apk + fi + else + print_warning "Local build test failed, but CI/CD setup continues" + fi +else + print_error "build.sh is not executable" + chmod +x build.sh + print_success "Fixed build.sh permissions" +fi + +# Repository setup verification +print_step "Verifying repository configuration..." + +# Check remote URL +remote_url=$(git remote get-url origin 2>/dev/null || echo "") +if [[ -z "$remote_url" ]]; then + print_error "No Git remote 'origin' configured" + echo "Please add your GitHub repository as remote:" + echo " git remote add origin https://github.com/username/repo.git" + exit 1 +else + print_success "Git remote configured: $remote_url" +fi + +# Check if we're on main or test branch +current_branch=$(git branch --show-current) +if [[ "$current_branch" != "main" ]] && [[ "$current_branch" != "test" ]]; then + print_warning "Not on main or test branch (current: $current_branch)" + echo "CI/CD pipeline triggers on main/test branches" +fi + +# Final steps +echo +print_step "Final setup steps..." +echo +echo "✅ CI/CD Setup Complete!" +echo +echo "📋 Next Steps:" +echo "1. Commit and push your changes:" +echo " git add ." +echo " git commit -m 'Add CI/CD pipeline'" +echo " git push origin main" +echo +echo "2. Check GitHub Actions tab in your repository" +echo "3. The pipeline will:" +echo " - Check for new Zabbix versions daily" +echo " - Build packages automatically" +echo " - Publish to your Gitea repository" +echo +echo "📖 Documentation:" +echo "- CI-CD-DOCS.md: Comprehensive pipeline documentation" +echo "- README.md: Usage and setup guide" +echo +echo "🔧 Manual Operations:" +echo "- Force build: Go to Actions tab → Zabbix APK Builder → Run workflow" +echo "- Test build: ./build.sh" +echo "- Check version: curl -s 'https://git.zabbix.com/rest/api/1.0/projects/ZBX/repos/zabbix/tags?limit=5'" +echo +print_success "Setup completed successfully! 🎉"