#!/bin/bash

# Color definitions
NC="\e[0m"
RED="\033[0;31m"
GREEN="\033[0;32m"
YELLOW="\033[1;33m"

# Get username from argument or stdin
if [ -n "$1" ]; then
    # Username provided as argument
    user="$1"
else
    # Read from stdin (for piped input)
    read -r user
fi

# Trim whitespace
user=$(echo "$user" | xargs)

# Check if username is empty
if [ -z "$user" ]; then
    echo -e "${RED}Error: Username tidak boleh kosong${NC}"
    exit 1
fi

# Check if user exists in vless config
if ! grep -qE "^#vl $user " "/etc/xray/config.json"; then
    echo -e "${RED}Error: User vless $user tidak ditemukan${NC}"
    exit 1
fi

# Get user info before deletion
exp=$(grep -E "^#vl $user " "/etc/xray/config.json" | cut -d ' ' -f 3 | head -n1)
uuid=$(grep -E "^#vl $user " "/etc/xray/config.json" | cut -d ' ' -f 4 | head -n1)

# Create akundelete directory if not exists
if [ ! -e /etc/vless/akundelete ]; then
    mkdir -p /etc/vless
    echo "" > /etc/vless/akundelete
fi

# Log deleted account
echo "### $user $exp $uuid" >> /etc/vless/akundelete

# Remove from xray config (both #vl and #vlg entries)
sed -i "/^#vl $user $exp/,/^},{/d" /etc/xray/config.json
sed -i "/^#vlg $user $exp/,/^},{/d" /etc/xray/config.json

# Remove user files
rm -f /etc/vless/${user}IP >/dev/null 2>&1
rm -f /home/vps/public_html/vless-${user}.txt >/dev/null 2>&1
rm -f /etc/vless/${user}login >/dev/null 2>&1
rm -f /etc/vless/akun/log-create-${user}.log >/dev/null 2>&1

# If it's a trial user, remove cron job
if [[ $user == trial-* ]]; then
    rm -f /etc/cron.d/trialvless${user} >/dev/null 2>&1
fi

# Restart xray service
systemctl restart xray >/dev/null 2>&1

# Success message
echo -e "${GREEN}Success: User vless $user telah dihapus${NC}"
echo -e "Username: $user"
if [ -n "$exp" ]; then
    echo -e "Expired: $exp"
fi
if [ -n "$uuid" ]; then
    echo -e "UUID: $uuid"
fi

exit 0

