69 lines
2.5 KiB
Bash
69 lines
2.5 KiB
Bash
#!/bin/bash
|
|
# Simple webhook receiver for Gitea
|
|
# Listens on port 9110 and triggers deploy.sh when called
|
|
#
|
|
# Usage: ./webhook-receiver.sh
|
|
# Test: curl -X POST http://127.0.0.1:9110/deploy
|
|
|
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
DEPLOY_DIR="$(dirname "$SCRIPT_DIR")"
|
|
DEPLOY_SCRIPT="$DEPLOY_DIR/deploy.sh"
|
|
LOG_FILE="$SCRIPT_DIR/webhook.log"
|
|
PORT="${WEBHOOK_PORT:-9110}"
|
|
SECRET="${WEBHOOK_SECRET:-}"
|
|
|
|
log() {
|
|
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
|
|
}
|
|
|
|
log "Webhook receiver starting on port $PORT..."
|
|
|
|
while true; do
|
|
# Listen for incoming HTTP requests using netcat
|
|
REQUEST=$(nc -l -p "$PORT" -q 1 2>/dev/null || nc -l "$PORT" 2>/dev/null)
|
|
|
|
# Parse the request
|
|
FIRST_LINE=$(echo "$REQUEST" | head -1)
|
|
METHOD=$(echo "$FIRST_LINE" | awk '{print $1}')
|
|
PATH=$(echo "$FIRST_LINE" | awk '{print $2}')
|
|
|
|
# Extract branch from payload (simple grep for "testing" branch)
|
|
if echo "$REQUEST" | grep -q '"ref".*"refs/heads/testing"'; then
|
|
BRANCH_MATCH="true"
|
|
else
|
|
BRANCH_MATCH="false"
|
|
fi
|
|
|
|
log "Received: $METHOD $PATH (testing branch: $BRANCH_MATCH)"
|
|
|
|
# Handle deploy endpoint
|
|
if [[ "$PATH" == "/deploy"* ]] && [[ "$METHOD" == "POST" ]]; then
|
|
if [[ "$BRANCH_MATCH" == "true" ]] || [[ "$PATH" == "/deploy?force=true" ]] || [[ -z "$REQUEST" ]]; then
|
|
log "Triggering deployment..."
|
|
|
|
# Run deploy in background and capture output
|
|
cd "$DEPLOY_DIR"
|
|
DEPLOY_OUTPUT=$("$DEPLOY_SCRIPT" 2>&1)
|
|
DEPLOY_EXIT=$?
|
|
|
|
log "Deploy exit code: $DEPLOY_EXIT"
|
|
echo "$DEPLOY_OUTPUT" >> "$LOG_FILE"
|
|
|
|
if [ $DEPLOY_EXIT -eq 0 ]; then
|
|
RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"status\":\"success\",\"message\":\"Deployment triggered\"}"
|
|
else
|
|
RESPONSE="HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"status\":\"error\",\"message\":\"Deployment failed\"}"
|
|
fi
|
|
else
|
|
log "Skipping - not testing branch"
|
|
RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"status\":\"skipped\",\"message\":\"Not testing branch\"}"
|
|
fi
|
|
elif [[ "$PATH" == "/health" ]]; then
|
|
RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nOK"
|
|
else
|
|
RESPONSE="HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nNot Found"
|
|
fi
|
|
|
|
echo -e "$RESPONSE"
|
|
done
|