#! /bin/bash -eu
set -o pipefail

IPV4_URL="https://cdn.vshosting.cloud/cdnip.txt"
IPV6_URL="https://cdn.vshosting.cloud/cdnip6.txt"

nginx_allow() (
    local ip_list="$1"
    echo "$ip_list" | awk '{print "allow " $0 ";"}'
)

nginx_deny() (
    local ip_list="$1"
    echo "$ip_list" | awk '{print "deny " $0 ";"}'
)

apache_allow() (
    local ip_list="$1"
    echo "$ip_list" | awk '{print "Require ip " $0}'
)

apache_deny() (
    local ip_list="$1"
    echo "$ip_list" | awk '{print "Require not ip " $0}'
)

nginx_realip() (
    local ip_list="$1"
    echo "$ip_list" | awk '{print "set_real_ip_from " $0 ";"}'
    echo ""
    echo "real_ip_header CDN-VSHOSTING-Real-IP;"
)

apache_rpaf() (
    local ip_list="$1"
    echo "RPAF_Enable On"
    echo "RPAF_Header CDN-VSHOSTING-Real-IP"
    echo ""
    echo "RPAF_ProxyIPs $(echo "$ip_list" | tr '\n' ' ')"
)

raw_list() (
    local ip_list="$1"
    echo "$ip_list"
)

main() (
    # check if number of arguments is 2
    if [ "$#" -ne 2 ] && [ "$#" -ne 3 ]; then
        echo "Usage: $0 <file_type> <output_file> [tmp_file]"
        echo "file_type: 'nginx_allow', 'nginx_deny', 'apache_allow', 'apache_deny', 'nginx_realip', 'apache_rpaf', 'raw'"
        echo "output_file: Path to the output file"
        echo "tmp_file: (Optional) Path to a temporary file, allows atomic writes"
        exit 1
    fi

    local file_type="$1"
    local output_file="$2"

    ip_list=$(curl -fsSL "$IPV4_URL")
    ip_list+=$'\n'
    ip_list+=$(curl -fsSL "$IPV6_URL")
    echo $ip_list

    case "$file_type" in
        nginx_allow)
            formatted_list=$(nginx_allow "$ip_list")
            ;;
        nginx_deny)
            formatted_list=$(nginx_deny "$ip_list")
            ;;
        apache_allow)
            formatted_list=$(apache_allow "$ip_list")
            ;;
        apache_deny)
            formatted_list=$(apache_deny "$ip_list")
            ;;
        nginx_realip)
            formatted_list=$(nginx_realip "$ip_list")
            ;;
        apache_rpaf)
            formatted_list=$(apache_rpaf "$ip_list")
            ;;
        raw)
            formatted_list=$(raw_list "$ip_list")
            ;;
        *)
            echo "Invalid file type: $file_type"
            exit 1
            ;;
    esac

    if [ "$#" -eq 3 ]; then
        tmp_file="$3"
        echo "$formatted_list" > "$tmp_file"
        mv "$tmp_file" "$output_file"
    else
        echo "$formatted_list" > "$output_file"
    fi
)

main "$@"