#!/bin/bash

set -eu -o pipefail

if [[ ${EUID} -ne 0 ]]; then
    echo "This script should be run as root." > /dev/stderr
    exit 1
fi

if [[ $# == 1 && "$1" == "--check" ]]; then
    echo "OK"
    exit 0
fi

[[ "${BOX_ENV}" == "test" ]] && exit

ipset flush cloudron_blocklist
ipset flush cloudron_blocklist6 || true # because kernel may not have ipv6

user_firewall_json="/home/yellowtent/platformdata/firewall/blocklist.txt"

if [[ -f "${user_firewall_json}" ]]; then
    # without the -n block, any last line without a new line won't be read it!
    while read -r line || [[ -n "$line" ]]; do
        [[ -z "${line}" ]] && continue # ignore empty lines
        [[ "$line" =~ ^#.*$ ]] && continue # ignore lines starting with #

        if [[ "$line" == *":"* ]]; then
            ipset add -! cloudron_blocklist6 "${line}" # the -! ignores duplicates
        else
            ipset add -! cloudron_blocklist "${line}" # the -! ignores duplicates
        fi
    done < "${user_firewall_json}"
fi
