#!/bin/bash
# Script to dispatch NetworkManager events
#
# Runs shows a login webpage on walled garden networks.
# See NetworkManager(8) for further documentation of the dispatcher events.
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
URL_HTTP="www.people.com.cn"
Intranet=$(dbus-send --system --print-reply \
    --dest=org.freedesktop.NetworkManager \
    /org/freedesktop/NetworkManager \
    org.freedesktop.DBus.Properties.Get \
    string:"org.freedesktop.NetworkManager" \
    string:"ConnectivityCheckSpareUri")
Intranet_URL=$(echo "$Intranet" | grep 'variant.*string' | awk '{print $3}' | tr -d '"')
# echo $Intranet_URL

curl_check() {
    curl -s -o /tmp/temp_url.txt "$1"
    location_href=$(grep -i 'location.href' /tmp/temp_url.txt | awk -F '[\r\n]' '{print $1}')
    # 打印location.href
    #echo "location.href: $location_href"
    # 删除临时文件
    if [ -f /tmp/temp_url.txt ]; then
        rm -f /tmp/temp_url.txt
    fi
    #匹配定向的网址
    regex="https?://[^'\"]*"
    if [[ $location_href =~ $regex ]]; then
        url="${BASH_REMATCH[0]}"
    fi
}

GetURL() {
    URL=$(curl -L -s -o /dev/null -w "%{url_effective}" "$1")
}

if [ -x "/usr/bin/logger" ]; then
    logger="/usr/bin/logger -s -t captive-portal"
else
    logger=":"
fi

wait_for_process() {
    PNAME=$1
    while [ -z "$(/usr/bin/pgrep $PNAME)" ]; do
        sleep 3
    done
}

open_url() {
    sudo -u "$user" --preserve-env=DISPLAY,XAUTHORITY,GTK_IM_MODULE -H xdg-open $1 2>&1 > /dev/null
}

#launch the browser, but on boot we need to wait that nm-applet starts
start_browser() {
    local user="$1"
    local display="$2"
    export DISPLAY="$display"
    export GTK_IM_MODULE=fcitx
    export XAUTHORITY="/home/$user/.Xauthority"
    # wait_for_process nm-applet
    wait_for_process kylin-nm

    $logger "Running browser as '$user' with display '$display' to login in captive portal"
    if [ "$location_href" ]; then
        response=$(curl -s -o /dev/null -w "%{http_code}" $url)
        echo "$?"
        if [ $? -ne 0 ]; then
            open_url $url
        elif [ -z $Intranet_URL ]; then
            open_url http://www.people.com.cn
        else
            open_url $Intranet_URL
        fi
    elif [[ $URL != *www.people.com.cn* ]] || [[ $URL != *$Intranet_URL* ]]; then
        open_url $URL 2>&1 >/dev/null
    elif [ -z "$Intranet_URL" ]; then
        open_url http://www.people.com.cn
    else
        open_url $Intranet_URL
    fi
}

check_user() {
    # Iterate over all logged in users and start a browser for each of them
    for user in $(who | awk '$NF ~ /\(:[0-9]+\)/ { print $1 }' | sort -u); do
        # Skip root user
        if [ "$user" = "root" ]; then
            continue
        fi
        # 使用loginctl user-status命令获取用户状态
        user_status=$(loginctl user-status $user 2>/dev/null)
        if [ $? -eq 0 ]; then
            if [[ $user_status == *"State: active"* ]]; then
                display=$(who | awk -v user="$user" '$1 ==user {print $NF}' | sed 's/[()]//g')
                # Start the browser for the user
                start_browser "$user" "$display" || $logger -p user.err "Failed for user: '$user' display: '$display'"
                break
            fi
        else
            $logger -p user.warning "User '$user' does not have an active desktop session"
            exit 0
        fi
    done
}

# Run the right scripts
case "$2" in
connectivity-change)
    $logger -p user.debug "dispatcher script triggered on connectivity change: $CONNECTIVITY_STATE"
    if [ "$CONNECTIVITY_STATE" = "PORTAL" ]; then
        if [[ -z "$Intranet_URL" ]]; then
            flag="0"
            GetURL $URL_HTTP
            curl_check $URL_HTTP
        else
            flag="1"
            GetURL $Intranet_URL
            curl_check $Intranet_URL
        fi
        if [[ $flag == "0" ]]; then
            if [[ "$URL" == *www.people.com.cn* ]] && [ -z "$location_href" ]; then
                echo "The network don't Moved Temporarily "
            else
                check_user
            fi
        else
            if [[ "$URL" == *$Intranet_URL* ]] && [ -z "$location_href" ]; then
                echo "The network don't spare Moved Temporarily "
            else
                check_user
            fi
        fi
    fi
    ;;
*)
    # In a down phase
    exit 0
    ;;
esac
