#!/bin/bash

# This is user's Personal access token with no special privileges
GH_TOKEN='ghp_xxxxxxxxxxxxxxxxxxxx'
# Fetch IP addresses using curl
IP_LIST=$(curl -L   -sH "Accept: application/vnd.github+json"   -H "Authorization: Bearer $GH_TOKEN"   -H "X-GitHub-Api-Version: 2022-11-28"   https://api.github.com/meta | jq -r .hooks | jq '.[]' | tr -d '"')

# Function to validate IPv4 address
validate_ipv4() {
    local IP="$1"
    # Regular expression to match IPv4 address format
    local IPV4_REGEX='^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'
    if [[ $IP =~ $IPV4_REGEX ]]; then
        return 0  # Valid IPv4 address
    else
        return 1 # Invalid IPv4 address
    fi
}

GENERATED_RULES=""
# Format fetched IP addresses as Shorewall rules
while read IP; do
        if validate_ipv4 "$IP"; then
                GENERATED_RULES+="ACCEPT      net:$IP        \$FW        tcp      443\n"
        else
                echo "IPv6 address. Not including in rules." >&2
        fi
done <<< "$IP_LIST"

# Append generated rules to Shorewall configuration file
grep -qxF "?COMMENT Github webhook IPs" /etc/shorewall/rules || echo "?COMMENT Github webhook IPs" >> /etc/shorewall/rules
EXISTING_RULES=$( echo -e "$GENERATED_RULES" | awk '{ print $2 }' )
grep "$EXISTING_RULES" /etc/shorewall/rules || echo -e "$GENERATED_RULES" >> /etc/shorewall/rules

