#!/bin/bash
# ============================================================================
# ZIVPN LICENSE CHECKER SCRIPT
# ============================================================================

# ----------------------------------------------------------------------------
# KONFIGURASI
# ----------------------------------------------------------------------------
LICENSE_URL="https://raw.githubusercontent.com/soakstore/izin/main/ip"
LICENSE_INFO_FILE="/etc/zivpn/.license_info"
EXPIRED_LOCK_FILE="/etc/zivpn/.expired"
TELEGRAM_CONF="/etc/zivpn/telegram.conf"
LOG_FILE="/var/log/zivpn_license.log"

# ----------------------------------------------------------------------------
# FUNGSI LOGGING
# ----------------------------------------------------------------------------
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# ----------------------------------------------------------------------------
# FUNGSI GET HOST (certificate atau IP publik dari icanhazip)
# ----------------------------------------------------------------------------
get_host() {
    local CERT_CN
    CERT_CN=$(openssl x509 -in /etc/zivpn/zivpn.crt -noout -subject 2>/dev/null | sed -n 's/.*CN = \([^,]*\).*/\1/p')

    if [ "$CERT_CN" == "zivpn" ] || [ -z "$CERT_CN" ]; then
        curl -4 -s https://icanhazip.com || curl -6 -s https://icanhazip.com
    else
        echo "$CERT_CN"
    fi
}

# ----------------------------------------------------------------------------
# FUNGSI GET ISP
# ----------------------------------------------------------------------------
get_isp() {
    curl -s ipinfo.io | jq -r '.org // "N/A"' | sed 's/^AS[0-9]\+ //'
}

# ----------------------------------------------------------------------------
# FUNGSI TELEGRAM
# ----------------------------------------------------------------------------
send_telegram_message() {
    local message="$1"

    if [ ! -f "$TELEGRAM_CONF" ]; then
        log "Telegram config not found, skipping notification."
        return
    fi

    source "$TELEGRAM_CONF"

    if [ -n "$TELEGRAM_BOT_TOKEN" ] && [ -n "$TELEGRAM_CHAT_ID" ]; then
        local api_url="https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage"
        curl -s -X POST "$api_url" \
            -d "chat_id=${TELEGRAM_CHAT_ID}" \
            --data-urlencode "text=${message}" \
            -d "parse_mode=Markdown" > /dev/null
        log "Telegram notification sent."
    else
        log "Telegram token/chat ID missing."
    fi
}

# ============================================================================
# MAIN
# ============================================================================
log "Starting license check..."

# Ambil IP server dari icanhazip
SERVER_IP=$(curl -4 -s https://icanhazip.com || curl -6 -s https://icanhazip.com)
SERVER_IP=$(echo "$SERVER_IP" | tr -d '[:space:]')

if [ -z "$SERVER_IP" ]; then
    log "Error: Failed to retrieve server IP from icanhazip."
    exit 1
fi

# Cek file lisensi lokal
if [ ! -f "$LICENSE_INFO_FILE" ]; then
    log "Local license file not found."
    exit 1
fi

source "$LICENSE_INFO_FILE"

# Ambil data lisensi remote
license_data=$(curl -s "$LICENSE_URL")
if [ $? -ne 0 ] || [ -z "$license_data" ]; then
    log "Failed to connect to license server."
    exit 1
fi

license_entry=$(echo "$license_data" | grep -w "$SERVER_IP")

# Jika IP tidak ada = revoked
if [ -z "$license_entry" ]; then
    if [ ! -f "$EXPIRED_LOCK_FILE" ]; then
        log "License REVOKED for IP ${SERVER_IP}"
        systemctl stop zivpn.service
        touch "$EXPIRED_LOCK_FILE"

        MSG="Lisensi untuk \`${CLIENT_NAME}\` (${SERVER_IP}) telah dicabut. Service dihentikan."
        send_telegram_message "$MSG"
    fi
    exit 0
fi

# Parse remote data
client_name_remote=$(echo "$license_entry" | awk '{print $1}')
expiry_date_remote=$(echo "$license_entry" | awk '{print $2}')
expiry_timestamp_remote=$(date -d "$expiry_date_remote" +%s)
current_timestamp=$(date +%s)

# Update lokal jika beda tanggal
if [ "$expiry_date_remote" != "$EXPIRY_DATE" ]; then
    log "Updating local expiry date to ${expiry_date_remote}"
    echo "CLIENT_NAME=${client_name_remote}" > "$LICENSE_INFO_FILE"
    echo "EXPIRY_DATE=${expiry_date_remote}" >> "$LICENSE_INFO_FILE"
    CLIENT_NAME=$client_name_remote
    EXPIRY_DATE=$expiry_date_remote
fi

# Cek expired
if [ "$expiry_timestamp_remote" -le "$current_timestamp" ]; then
    if [ ! -f "$EXPIRED_LOCK_FILE" ]; then
        log "License EXPIRED for ${SERVER_IP}"
        systemctl stop zivpn.service
        touch "$EXPIRED_LOCK_FILE"

        host=$(get_host)
        isp=$(get_isp)

        /usr/local/bin/zivpn_helper.sh expiry-notification \
            "$host" "$SERVER_IP" "$CLIENT_NAME" "$isp" "$EXPIRY_DATE"
    fi
else
    if [ -f "$EXPIRED_LOCK_FILE" ]; then
        log "License RENEWED for ${SERVER_IP}"
        rm "$EXPIRED_LOCK_FILE"
        systemctl start zivpn.service

        host=$(get_host)
        isp=$(get_isp)

        /usr/local/bin/zivpn_helper.sh renewed-notification \
            "$host" "$SERVER_IP" "$CLIENT_NAME" "$isp" "$EXPIRY_DATE"
    else
        log "License active."
    fi
fi

log "License check finished."
exit 0