101 lines
2.9 KiB
Bash
Executable File
101 lines
2.9 KiB
Bash
Executable File
#! /bin/bash
|
|
|
|
# https://unix.stackexchange.com/a/423052
|
|
function find_free_port {
|
|
comm -23 <(seq 49152 65535 | sort) <(ss -Htan | awk '{print $4}' | cut -d':' -f2 | sort -u) | shuf | head -n 1
|
|
}
|
|
|
|
# gen_webhook "REPO_URL"
|
|
#function gen_webhook {
|
|
# echo "{ \"project\": { \"git_http_url\": \"$1\" } }"
|
|
#}
|
|
|
|
function gen_webhook() {
|
|
export repo_url="$2"
|
|
envsubst < "$BATS_TEST_DIRNAME"/"$1"
|
|
# NOTE: Below does not work because dirname $0 is /usr/libexec/bats-core/
|
|
#envsubst < "$(dirname "$0")"/"$1"
|
|
}
|
|
|
|
# send_webhook "ENDPOINT" "PAYLOAD" "SECRET" "HEADER"
|
|
# ENDPOINT: where to send the request
|
|
# PAYLOAD: POST body
|
|
# SECRET: the secret for this transaction
|
|
# HEADER: where to store the secret
|
|
function send_webhook {
|
|
TMPFILE="$(mktemp)"
|
|
echo -n "$2" > $TMPFILE
|
|
# To prevent race conditions where curl is started while $TMPFILE is still empty
|
|
sync
|
|
|
|
# We can make a few attempts, just in case the webserver hasn't started yet
|
|
n=0
|
|
status=""
|
|
while [[ "$status" != "0" ]]; do
|
|
if [ $n -eq 3 ]; then
|
|
# Failed to reach server after 3 attempts
|
|
return 1;
|
|
fi
|
|
# --data-binary so that newlines aren't broken
|
|
# (otherwise, signature won't match)
|
|
outputFile="$(mktemp)"
|
|
http_status="$(curl --header "Content-Type: application/json" \
|
|
--output "$outputFile" \
|
|
--header ""$4": "$3"" \
|
|
--request POST \
|
|
--data-binary @$TMPFILE \
|
|
-s -w "%{http_code}" \
|
|
"$1")"
|
|
status=$?
|
|
rm $TMPFILE
|
|
# Requested succeeded, break out of loop
|
|
if [ $status -eq 0 ]; then
|
|
if [[ ! "$http_status" = 200 ]]; then
|
|
echo "ERROR: Failed with server returning code $http_status. Body:"
|
|
cat "$outputFile"
|
|
rm "$outputFile"
|
|
return 2
|
|
fi
|
|
return 0;
|
|
fi
|
|
((n++))
|
|
sleep 0.1
|
|
done
|
|
}
|
|
|
|
# https://stackoverflow.com/a/7385197
|
|
function hash_hmac {
|
|
digest="$1"
|
|
data="$2"
|
|
key="$3"
|
|
shift 3
|
|
# Don't print (stdin)= ...
|
|
echo -n "$data" | openssl dgst "-$digest" -hmac "$key" | awk '{print $2}'
|
|
}
|
|
|
|
# Used to find executable from several likely locations
|
|
# Pass any number of arguments, returns the first one that's
|
|
# an executable file. If a file exists but is not executable,
|
|
# a warning is printed
|
|
# Output is in the form of "WARNING:\nresult" so if exit code is 0 you can safely fetch the last line to find the result
|
|
findBin () {
|
|
#if [ $# -eq 0 ]; exit; fi
|
|
while [ ! $# -eq 0 ]; do
|
|
# Resolve symlinks
|
|
f="$(readlink -m "$1")"
|
|
shift
|
|
if [ ! -f "$f" ]; then
|
|
echo "DEBUG: "$f" does not exist"
|
|
continue;
|
|
fi
|
|
if [ ! -x "$f" ]; then
|
|
echo "WARNING: "$f" exists but is not executable" >&2
|
|
continue
|
|
fi
|
|
echo "$f"
|
|
return
|
|
done
|
|
# nothing found
|
|
return 1
|
|
}
|