#!/bin/bash

# Copyright (c) 2020-2024, Windscribe Limited. All rights reserved.
# Manages /etc/gai.conf to prioritize IPv4 when VPN blocks IPv6
# Usage: gai-ipv4-priority up|down

PATH="$PATH:/usr/local/sbin:/usr/sbin:/sbin"

GAI_CONF="/etc/gai.conf"
WINDSCRIBE_MARKER="# Added by Windscribe to prioritize IPv4 when IPv6 is blocked"

# Enable IPv4 priority by modifying gai.conf
gai_ipv4_priority_up()
{
    # Check if IPv4 priority is already configured
    if [ -f "$GAI_CONF" ] && grep -q "^precedence ::ffff:0:0/96  100" "$GAI_CONF" 2>/dev/null; then
        echo "IPv4 priority already configured in $GAI_CONF"
        return 0
    fi

    # Add IPv4 priority configuration
    # This gives IPv4-mapped addresses higher precedence than native IPv6
    echo "precedence ::ffff:0:0/96  100  $WINDSCRIBE_MARKER" >> "$GAI_CONF"

    echo "IPv4 priority configured in $GAI_CONF"
}

# Restore original gai.conf
gai_ipv4_priority_down()
{
    if [ ! -f "$GAI_CONF" ]; then
        echo "No gai.conf modifications to restore"
        return 0
    fi

    local modified=false

    # Remove legacy format: marker on its own line followed by the precedence line
    if grep -qF "$WINDSCRIBE_MARKER" "$GAI_CONF" 2>/dev/null; then
        sed -i "\|^${WINDSCRIBE_MARKER}$|{N;/\nprecedence ::ffff:0:0\/96  100$/d;}" "$GAI_CONF"
        modified=true
    fi

    # Remove any lines containing our marker (current format: precedence + marker on same line)
    if grep -qF "$WINDSCRIBE_MARKER" "$GAI_CONF" 2>/dev/null; then
        sed -i "\|${WINDSCRIBE_MARKER}|d" "$GAI_CONF"
        modified=true
    fi

    if [ "$modified" = true ]; then
        # If the file is now empty (only whitespace), remove it
        if ! grep -q '[^[:space:]]' "$GAI_CONF" 2>/dev/null; then
            rm -f "$GAI_CONF"
        fi
        echo "Removed Windscribe IPv4 priority entries from $GAI_CONF"
    else
        echo "No gai.conf modifications to restore"
    fi
}

main()
{
    local action="$1"

    if [[ $action == "up" ]]; then
        gai_ipv4_priority_up
    elif [[ $action == "down" ]]; then
        gai_ipv4_priority_down
    else
        echo "Usage: gai-ipv4-priority up|down"
        return 1
    fi
}

main "$@"
