#!/usr/bin/zsh
# Script Version: 01
# Description: Script to obtain the public IP and post it to a server securely.

# Define the path to store the token
TOKEN_FILE="/root/scripts/token.txt"
LOG_FILE="/var/log/ipgetpost.log"
IP_URL="http://ip.dynproxy.net"

# Function to log messages
log_message() {
    print "$(date): $1" >> "$LOG_FILE"
}

# Set umask to ensure files are created with the correct permissions
umask 077

# Check if the token file already exists, if not, generate a new token
if [ ! -f "$TOKEN_FILE" ]; then
    # Generate a 32-character hexadecimal token
    TOKEN=$(openssl rand -hex 16)
    if [ $? -ne 0 ]; then
        log_message "Failed to generate token"
        exit 1
    fi
    print "$TOKEN" > "$TOKEN_FILE" || {
        log_message "Failed to write token to $TOKEN_FILE"
        exit 1
    }
    log_message "Token created and saved to $TOKEN_FILE"
else
    TOKEN=$(< "$TOKEN_FILE")
    if [ $? -ne 0 ]; then
        log_message "Failed to read token from $TOKEN_FILE"
        exit 1
    fi
    log_message "Token read from $TOKEN_FILE"
fi

# Fetch the current public IP
CURRENT_IP=$(curl -s -m 10 "$IP_URL")
if [ $? -ne 0 ] || [ -z "$CURRENT_IP" ]; then
    log_message "Failed to obtain IP address from $IP_URL"
    exit 1
fi

# Log the IP (do not log the token)
log_message "Posting IP $CURRENT_IP"

# Post the IP and token to the main server using HTTPS, retry if fails
MAX_RETRIES=3
RETRY_DELAY=5

# Retry loop: Attempt to post the IP address to the server up to MAX_RETRIES times, with a delay between attempts.
# This helps handle potential network issues or server availability problems.
for i in {1..$MAX_RETRIES}; do
    RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
               -H "Content-Type: application/x-www-form-urlencoded" \
               --data-urlencode "ip=$CURRENT_IP" \
               --data-urlencode "token=$TOKEN" \
               $IP_URL/update_ip)

    if [ "$RESPONSE" -eq 200 ]; then
        log_message "IP posted successfully"
        exit 0
    else
        log_message "Failed to post IP. Response code: $RESPONSE. Attempt $i of $MAX_RETRIES."
        sleep $RETRY_DELAY
    fi
done

log_message "Failed to post IP after $MAX_RETRIES attempts"
exit 1