#!/bin/bash

SERVER='xxx'
USER='xxx'
PASSWD='xxx'

RESOURCES_URL="https://$SERVER:8007/api2/extjs/cluster/resources"
TICKET_URL="https://$SERVER:8007/api2/extjs/access/ticket"

FILE='ticket'
CSRFPreventionToken=''
TICKET=''

# 当前时间戳
CURRENT_TIMESTAMP=$(date '+%s')

get_ticket() {
    RESULT=$(curl -k -X POST -d "username=$USER&password=$PASSWD&realm=pam" $TICKET_URL)
    TICKET=$(echo "$RESULT" | jq -r '.data.ticket')
    CSRFPreventionToken=$(echo "$RESULT" | jq -r '.data.CSRFPreventionToken')
    echo "$TICKET;$CSRFPreventionToken;$CURRENT_TIMESTAMP" > "$FILE"
}

# 检查文件是否存在
if [ -f "$FILE" ]; then
#    echo "文件 $FILE 存在，解析内容..."

    # 逐行读取文件并解析 ticket 和时间戳
    while IFS=';' read -r TICKET_f CSRFPreventionToken_f TIMESTAMP; do
#        echo "Ticket: $TICKET_f"
#        echo "CSRFPreventionToken: $CSRFPreventionToken_f"
#        echo "时间戳: $TIMESTAMP"
        TICKET=$TICKET_f
        CSRFPreventionToken=$CSRFPreventionToken_f
        time_diff=$((CURRENT_TIMESTAMP - TIMESTAMP))
        if [ $time_diff -ge 3600 ]; then
            get_ticket
        fi
    done < "$FILE"
else
    get_ticket
fi

CONTENT=""
TARGET_DIR="/opt/prometheus/targets"
TARGET_NEW="$TARGET_DIR/vcloud_ips.yml.new"
TARGET="$TARGET_DIR/vcloud_ips.yml"
TARGET_CONTENT="- targets:"$'\n'

get_resources() {
    RESULT=$(curl -k -b "PVEAuthCookie=$TICKET" $RESOURCES_URL)
    VMLIST=$(echo "$RESULT" | jq -r '.data | map(select(.status == "running" and .agent == 1)) | sort_by(.vmid) | .[] | "\(.node),\(.vmid)"')
    while IFS=, read -r node vmid; do
        echo "VM: $vmid, Node: $node"

        GETNET_URL="https://$SERVER:8007/api2/extjs/nodes/$node/qemu/$vmid/agent/network-get-interfaces"
        NETWORKS=$(curl -k -b "PVEAuthCookie=$TICKET" $GETNET_URL)

IP=$(echo "$NETWORKS" | jq -r '
    .data.result[]
    | .["ip-addresses"][]?
    | select(.["ip-address-type"] == "ipv4")
    | select(
      (
        (.["ip-address"] | startswith("10.")) or
        (.["ip-address"] | test("^172\\.(1[6-9]|2[0-9]|3[0-1])\\.")) or
        (.["ip-address"] | startswith("192.168."))
      ) and
      (
        (.["ip-address"] | test("^172\\.17\\.")) | not
      )
    )
    | .["ip-address"]
')

        CONTENT+="$vmid,$node,$IP"$'\n'
        TARGET_CONTENT+="  - $IP"$'\n'
    done < <(echo "$VMLIST")

    echo -e "$CONTENT" > "vmlist"

    if [ ! -d "$TARGET_DIR" ]; then
        mkdir -p $TARGET_DIR
    fi

    echo -e "$TARGET_CONTENT" > "$TARGET_NEW"
    mv $TARGET_NEW $TARGET
}
get_resources

