#!/bin/bash

# Test the vps proxy is work
# if work, record to access.log in . folder
# if not work, record to error.log in . folder and push msg to dingtalk api

# SET THE ARGUMENTS
BWH_PROXY="http://127.0.0.1:1099"
JP_PROXY="http://127.0.0.1:1080"
ALL_PROXY=("BWH_PROXY" "JP_PROXY")
proxy_var=""
ip_address="https://v4.ident.me"
access_address="https://pac-9d7.pages.dev/access"
error_log="error.log"
access_log="access.log"
webhook="https://oapi.dingtalk.com/robot/send?access_token=b2a92184affebb3f26dfcab1eff9571b46c27a85380fd9ff56ca4c66cf93e1a1"
keyword="BWH:"

# Set directory
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
cd "$SCRIPT_DIR" || exit
my_proxy=""
# Function to log errors and send dingtalk message
log_error() {
    local error_msg=$1
    echo "$(date "+%Y-%m-%d %H:%M:%S") $error_msg $get_ip $get_realip" >> "$error_log"
    local msg="$keyword ERROR:\n $proxy_var  $error_msg \n$(date "+%Y-%m-%d %H:%M:%S")"
    curl -sL "$webhook" \
        -H 'Content-Type: application/json' \
        -d "{\"msgtype\": \"text\",\"text\": {\"content\":\"$msg\"}}"
}

for proxy_var in "${ALL_PROXY[@]}"; do
    # Get the real IP
    export all_proxy=""
    get_realip=$(curl -sL "$ip_address" || echo "GET_DIRECT_IP_FAILED")

    # Set proxy
    export all_proxy=${!proxy_var}

    # Get proxy IP
    get_ip=$(curl -sL "$ip_address" || echo "GET_${proxy_var}_IP_FAILED")

    # Get access key words
    get_pass=$(curl -sL "$access_address" || echo "${proxy_var}_CURL_CF_FAILED")
    export all_proxy=""

    if [ "$get_pass" == "${proxy_var}_CURL_CF_FAILED" ]; then
        log_error "$get_pass"
    else
        echo "$(date "+%Y-%m-%d %H:%M:%S") $get_pass $get_ip $get_realip" >> "$access_log"
    fi
done

# Check if log file is bigger than max size
max_size=104857600
date1=$(date +"%Y%m%d")
if [ -f "$access_log" ]; then
    file_size=$(stat -c%s "$access_log")
    if [ "$file_size" -gt "$max_size" ]; then
        tar czvf "$access_log-$date1.tar.gz" "$access_log"
        rm "$access_log"
        touch "$access_log"
    fi
fi


