set -eu
: "${RK_REPO:?rk sets this; run this script through rk setup}"
: "${RK_TRUNK_BRANCH:?rk sets this; run this script through rk setup}"
project="$(printf '%s' "$RK_REPO" | sed 's|/|%2F|g')"
compact() { tr -d ' \t\r\n'; }
if glab api "projects/$project/protected_branches/$RK_TRUNK_BRANCH" >/dev/null 2>&1; then
current="$(glab api "projects/$project/protected_branches/$RK_TRUNK_BRANCH" | compact)"
levels="$(printf '%s' "$current" | grep -o '"push_access_levels":\[[^]]*\]' || true)"
merge_levels="$(printf '%s' "$current" | grep -o '"merge_access_levels":\[[^]]*\]' || true)"
grants="$(printf '%s' "$levels" | grep -o '{' | grep -c . || true)"
merge_grants="$(printf '%s' "$merge_levels" | grep -o '{' | grep -c . || true)"
if [ "$grants" = "1" ] && printf '%s' "$levels" | grep -q '"access_level":0' \
&& [ "$merge_grants" = "1" ] && printf '%s' "$merge_levels" | grep -q '"access_level":40'; then
glab api -X PATCH "projects/$project/protected_branches/$RK_TRUNK_BRANCH" \
-F allow_force_push=false >/dev/null
else
glab api -X DELETE "projects/$project/protected_branches/$RK_TRUNK_BRANCH" >/dev/null
glab api -X POST "projects/$project/protected_branches" \
-f "name=$RK_TRUNK_BRANCH" -F push_access_level=0 -F merge_access_level=40 \
-F allow_force_push=false >/dev/null
fi
else
glab api -X POST "projects/$project/protected_branches" \
-f "name=$RK_TRUNK_BRANCH" -F push_access_level=0 -F merge_access_level=40 \
-F allow_force_push=false >/dev/null
fi
glab api -X PUT "projects/$project" \
-F only_allow_merge_if_pipeline_succeeds=true -f merge_method=ff -f squash_option=always \
-f 'squash_commit_template=%{title}' >/dev/null
echo "check: prints the protection, the pipeline requirement, the merge method, the squash setting, and the squash template"
glab api "projects/$project/protected_branches/$RK_TRUNK_BRANCH" | compact | grep -o "\"name\":\"$RK_TRUNK_BRANCH\""
glab api "projects/$project" | compact | grep -o '"only_allow_merge_if_pipeline_succeeds":[a-z]*'
glab api "projects/$project" | compact | grep -o '"merge_method":"[^"]*"'
glab api "projects/$project" | compact | grep -o '"squash_option":"[^"]*"'
glab api "projects/$project" | compact | grep -o '"squash_commit_template":"[^"]*"'