#!/bin/bash
#27/01/2021
clear
clear
msg -bar
myip=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0' | head -n1`;
myint=`ifconfig | grep -B1 "inet addr:$myip" | head -n1 | awk '{print $1}'`;
NOM=`less /etc/VPS-MX/controlador/nombre.log` > /dev/null 2>&1
NOM1=`echo $NOM` > /dev/null 2>&1
IDB=`less /etc/VPS-MX/controlador/IDT.log` > /dev/null 2>&1
IDB1=`echo $IDB` > /dev/null 2>&1
declare -A TIMEUS 
SCPdir="/etc/VPS-MX"
SCPdir2="${SCPdir}/herramientas"
SCPusr="${SCPdir}/controlador"
MyPID="${SCPusr}/pid-vps-mx"
MyTIME="${SCPusr}/time-vps-mx"
USRdatabase="${SCPdir}/VPS-MXuser"
VERY="$(ps aux|grep "${SCPusr}/usercodes verificar"| grep -v grep)"
VERY2="$(ps aux|grep "${SCPusr}/usercodes desbloqueo"| grep -v grep)"
dirapache="/usr/local/lib/ubuntn/apache/ver" && [[ ! -d ${dirapache} ]] && exit
[[ -e ${MyPID} ]] && source ${MyPID} || touch ${MyPID}
[[ -e ${MyTIME} ]] && source ${MyTIME} || touch ${MyTIME}
[[ ! -e ${USRdatabase} ]] && touch ${USRdatabase}
sort ${USRdatabase} | uniq > ${USRdatabase}tmp
mv -f ${USRdatabase}tmp ${USRdatabase}
# Open VPN
newclient () {
#Nome #Senha
usermod -p $(openssl passwd -1 $2) $1
  while [[ ${newfile} != @(s|S|y|Y|n|N) ]]; do
msg -bar
   read -p "Crear Archivo OpenVPN? [S/N]: " -e -i S newfile
   tput cuu1 && tput dl1
  done
if [[ ${newfile} = @(s|S) ]]; then
	# Generates the custom client.ovpn
	rm -rf /etc/openvpn/easy-rsa/pki/reqs/$1.req
	rm -rf /etc/openvpn/easy-rsa/pki/issued/$1.crt
	rm -rf /etc/openvpn/easy-rsa/pki/private/$1.key
	cd /etc/openvpn/easy-rsa/
	./easyrsa build-client-full $1 nopass > /dev/null 2>&1
	cd
	
	cp /etc/openvpn/client-common.txt ~/$1.ovpn
	echo "<ca>" >> ~/$1.ovpn
	cat /etc/openvpn/easy-rsa/pki/ca.crt >> ~/$1.ovpn
	echo "</ca>" >> ~/$1.ovpn
	echo "<cert>" >> ~/$1.ovpn
	cat /etc/openvpn/easy-rsa/pki/issued/$1.crt >> ~/$1.ovpn
	echo "</cert>" >> ~/$1.ovpn
	echo "<key>" >> ~/$1.ovpn
	cat /etc/openvpn/easy-rsa/pki/private/$1.key >> ~/$1.ovpn
	echo "</key>" >> ~/$1.ovpn
	echo "<tls-auth>" >> ~/$1.ovpn
	cat /etc/openvpn/ta.key >> ~/$1.ovpn
	echo "</tls-auth>" >> ~/$1.ovpn
	
  while [[ ${ovpnauth} != @(s|S|y|Y|n|N) ]]; do
    read -p "$(fun_trans "Colocar autenticacion de usuario en el archivo")? [S/N]: " -e -i S ovpnauth
    tput cuu1 && tput dl1
  done
  [[ ${ovpnauth} = @(s|S) ]] && sed -i "s;auth-user-pass;<auth-user-pass>\n$1\n$2\n</auth-user-pass>;g" ~/$1.ovpn
  cd $HOME
  zip ./$1.zip ./$1.ovpn > /dev/null 2>&1
  rm ./$1.ovpn > /dev/null 2>&1

  echo -e "\033[1;31m$(fun_trans "Archivo creado"): ($HOME/$1.zip)"
 fi
}

unlockall2 () {
for user in $(cat /etc/passwd |awk -F : '$3 > 900 {print $1}' |grep -v "rick" |grep -vi "nobody")
do
userpid=$(ps -u $user |awk {'print $1'})

usermod -U $user &>/dev/null
done
}

eliminar_all () {
clear
clear
msg -bar
msg -tit
echo -e "\033[1;31m       BORRAR TODOS LOS USUARIOS REGISTRADOS"
msg -bar
read -p "   ►► Enter para Continuar  o CTRL + C Cancelar ◄◄"
echo ""
service dropbear stop &>/dev/null
service sshd stop &>/dev/null
service ssh stop &>/dev/null
service stunnel4 stop &>/dev/null
service squid stop &>/dev/null
for user in $(cat /etc/passwd |awk -F : '$3 > 900 {print $1}' |grep -v "rick" |grep -vi "nobody")
do
userpid=$(ps -u $user |awk {'print $1'})
kill "$userpid" 2>/dev/null
userdel $user
echo -e "\033[1;32mUSUARIO:\033[1;33m $user \033[1;31mEliminado"
done
rm -rf ${SCPdir}/VPS-MXuser
service sshd restart &>/dev/null
service ssh restart &>/dev/null
service dropbear start &>/dev/null
service stunnel4 start &>/dev/null
service squid restart &>/dev/null
rm -rf ${SCPdir}/VPS-MX-userlock &>/dev/null
rm -rf /etc/VPS-MX/controlador/Limiter.log &>/dev/null
unlockall2
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}

reset_contador () {
clear 
clear
msg -bar
msg -tit
echo -e "\033[1;33m          REINICIAR CONTADOR DE BLOQUEOS"
msg -bar
echo -e "\033[1;97m !! Usar unicamente cuando en el apartado del contador\nmarque alguna cantidad erronea. ¡¡"
echo ""
echo -e "\033[1;91m ## Cancelar Precione CTRL+C"
msg -bar
read -p "        ►► Presione enter para continuar ◄◄"
rm -rf /etc/VPS-MX/VPS-MX-userlock
rm -rf /etc/VPS-MX/controlador/Limiter.log
unlockall2
msg -bar
echo -e "\033[1;92m           ¡¡CONTADORES REINICIADOS!!"
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}
SPR &
droppids () {
local pids

local portasVAR=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN")
local NOREPEAT
local reQ
local Port
while read port; do
reQ=$(echo ${port}|awk '{print $1}')
Port=$(echo {$port} | awk '{print $9}' | awk -F ":" '{print $2}')
[[ $(echo -e $NOREPEAT|grep -w "$Port") ]] && continue
NOREPEAT+="$Port\n"
case ${reQ} in

dropbear)
[[ -z $DPB ]] && local DPB="\033[1;31m DROPBEAR: \033[1;32m"
DPB+="$Port ";;

esac
done <<< "${portasVAR}"


[[ ! -z $DPB ]] && echo -e $DPB 

local port_dropbear="$DPB"
#cat /var/log/auth.log|grep "$(date|cut -d' ' -f2,3)" > /var/log/authday.log
cat /var/log/auth.log|tail -1000 > /var/log/authday.log
local log=/var/log/authday.log
local loginsukses='Password auth succeeded'
[[ -z $port_dropbear ]] && return 1
for port in `echo $port_dropbear`; do
 for pidx in $(ps ax |grep dropbear |grep "$port" |awk -F" " '{print $1}'); do
  pids="${pids}$pidx\n"
 done
done
for pid in `echo -e "$pids"`; do
  pidlogs=`grep $pid $log |grep "$loginsukses" |awk -F" " '{print $3}'`
  i=0
    for pidend in $pidlogs; do
    let i++
    done
    if [[ $pidend ]]; then
    login=$(grep $pid $log |grep "$pidend" |grep "$loginsukses")
    PID=$pid
    user=`echo $login |awk -F" " '{print $10}' | sed -r "s/'//g"`
    waktu=$(echo $login |awk -F" " '{print $2"-"$1,$3}')
    [[ -z $user ]] && continue
	echo "$user|$PID|$waktu"
    fi
done
}

block_userfun () {
local USRloked="/etc/VPS-MX/VPS-MX-userlock"
local LIMITERLOG="${USRdatabase}/Limiter.log"
local LIMITERLOG2="${USRdatabase}/Limiter2.log"
if [[ $2 = "-loked" ]]; then 
[[ $(cat ${USRloked}|grep -w "$1") ]] && return 1
echo " $1 (BLOCK-MULTILOGIN) $(date +%r--%d/%m/%y)"
limseg="$(less /etc/VPS-MX/controlador/tiemdes.log)"
KEY="862633455:AAGJ9BBJanzV6yYwLSemNAZAVwn7EyjrtcY"
URL="https://api.telegram.org/bot$KEY/sendMessage"
MSG="⚠️ AVISO DE VPS: $NOM1 ⚠️
🔹 CUENTA: $1 
❗️📵 BLOCK FIJO/TEMPORAL 📵❗️
🔓( AUTOUNLOCK EN $limseg SEGUNDOS) 🔓"
curl -s --max-time 10 -d "chat_id=$IDB1&disable_web_page_preview=1&text=$MSG" $URL &>/dev/null

pkill -u $1 &>/dev/null

fi
if [[ $(cat ${USRloked}|grep -w "$1") ]]; then
usermod -U "$1" &>/dev/null
[[ -e ${USRloked} ]] && {
   newbase=$(cat ${USRloked}|grep -w -v "$1")
   [[ -e ${USRloked} ]] && rm ${USRloked}
   for value in `echo ${newbase}`; do
   echo $value >> ${USRloked}
   done
   }
[[ -e ${LIMITERLOG} ]] && [[ $(cat ${LIMITERLOG}|grep -w "$1") ]] && {
   newbase=$(cat ${LIMITERLOG}|grep -w -v "$1")
   [[ -e ${LIMITERLOG} ]] && rm ${LIMITERLOG}
   for value in `echo ${newbase}`; do
   echo $value >> ${LIMITERLOG}
   echo $value >> ${LIMITERLOG}    
   done
}
return 1
else
usermod -L "$1" &>/dev/null
pkill -u $1 &>/dev/null

# droplim=`droppids|grep -w "$1"|cut -d'|' -f2` 
# kill -9 $droplim &>/dev/null

droplim=`dropbear_pids|grep -w "$1"|cut -d'|' -f2` 
kill -9 $droplim &>/dev/null

echo $1 >> ${USRloked}
#notifi &>/dev/null
return 0
fi

} 

block_user () {
clear
clear
msg -bar
local USRloked="/etc/VPS-MX/VPS-MX-userlock"
[[ ! -e ${USRloked} ]] && touch ${USRloked}
usuarios_ativos=($(mostrar_usuarios))
if [[ -z ${usuarios_ativos[@]} ]]; then
msg -tit
msg -verm "$(fun_trans " BLOCK/UNBLOCK | Ningun Usuario Registrado")"
msg -bar
return 1
else
msg -tit
msg -ama "$(fun_trans " BLOCK/UNBLOCK | Usuarios Activos del Servidor")"
msg -bar
Numb=0
for us in $(echo ${usuarios_ativos[@]}); do
if [[ $(cat ${USRloked}|grep -w "${us}") ]]; then
msg -ne "[$Numb] ->" && echo -e "\033[1;33m ${us} \033[1;31m[Loked]"
else
msg -ne "[$Numb] ->" && echo -e "\033[1;33m ${us} \033[1;32m[Unlocked]"
fi
let Numb++
done
msg -bar
fi
msg -ama "$(fun_trans "Escriba o Seleccione Un Usuario")"
msg -bar
unset selection
while [[ ${selection} = "" ]]; do
echo -ne "\033[1;37mSeleccione: " && read selection
tput cuu1 && tput dl1
done
if [[ ! $(echo "${selection}" | egrep '[^0-9]') ]]; then
usuario_del="${usuarios_ativos[$selection]}"
else
usuario_del="$selection"
fi
[[ -z $usuario_del ]] && {
     msg -verm "$(fun_trans "Error, Usuario Invalido")"
     msg -bar
     return 1
     }
[[ ! $(echo ${usuarios_ativos[@]}|grep -w "$usuario_del") ]] && {
     msg -verm "$(fun_trans "Error, Usuario Invalido")"
     msg -bar
     return 1
     }
msg -ne "$(fun_trans "Usuario Seleccionado"): " && echo -ne "$usuario_del "
block_userfun "$usuario_del" && msg -verm "[$(fun_trans "Bloqueado")]" || msg -verd "[$(fun_trans "Desbloqueado")]"
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}
msg -bar3
add_user () {
Fecha=`date +%d-%m-%y-%R`
#nome senha Dias limite
[[ $(cat /etc/passwd |grep $1: |grep -vi [a-z]$1 |grep -v [0-9]$1 > /dev/null) ]] && return 1
valid=$(date '+%C%y-%m-%d' -d " +$3 days") && datexp=$(date "+%F" -d " + $3 days")
useradd -M -s /bin/false $1 -e ${valid} > /dev/null 2>&1 || return 1
(echo $2; echo $2)|passwd $1 2>/dev/null || {
    userdel --force $1
    return 1
    }
[[ -e ${USRdatabase} ]] && {
   newbase=$(cat ${USRdatabase}|grep -w -v "$1")
   echo "$1|$2|${datexp}|$4" > ${USRdatabase}
   for value in `echo ${newbase}`; do
   echo $value >> ${USRdatabase}
   echo $value >> ${SCPdir}/B-VPS-MXuser/VPS-MXuser-"$Fecha"
   done
   } || echo "$1|$2|${datexp}|$4" > ${USRdatabase}
}
renew_user_fun () {
#nome dias
datexp=$(date "+%F" -d " + $2 days") && valid=$(date '+%C%y-%m-%d' -d " + $2 days")
chage -E $valid $1 2> /dev/null || return 1
[[ -e ${USRdatabase} ]] && {
   newbase=$(cat ${USRdatabase}|grep -w -v "$1")
   useredit=$(cat ${USRdatabase}|grep -w "$1")
   pass=$(echo $useredit|cut -d'|' -f2)
   limit=$(echo $useredit|cut -d'|' -f4)
   echo "$1|$pass|${datexp}|$limit" > ${USRdatabase}
   for value in `echo ${newbase}`; do
   echo $value >> ${USRdatabase}
   done
   }
}
edit_user_fun () {
#nome senha dias limite
(echo "$2" ; echo "$2" ) |passwd $1 > /dev/null 2>&1 || return 1
datexp=$(date "+%F" -d " + $3 days") && valid=$(date '+%C%y-%m-%d' -d " + $3 days")
chage -E $valid $1 2> /dev/null || return 1
[[ -e ${USRdatabase} ]] && {
   newbase=$(cat ${USRdatabase}|grep -w -v "$1")
   echo "$1|$2|${datexp}|$4" > ${USRdatabase}
   for value in `echo ${newbase}`; do
   echo $value >> ${USRdatabase}
   done
   } || echo "$1|$2|${datexp}|$4" > ${USRdatabase}
}
rm_user () {
#nome
userdel --force "$1" &>/dev/null || return 1
[[ -e ${USRdatabase} ]] && {
   newbase=$(cat ${USRdatabase}|grep -w -v "$1")
   for value in `echo ${newbase}`; do
   echo $value >> ${USRdatabase}
   done
   }
}
mostrar_usuarios () {
for u in `awk -F : '$3 > 900 { print $1 }' /etc/passwd | grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do
echo "$u"
done
}
dropbear_pids () {
local pids

local portasVAR=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN")
local NOREPEAT
local reQ
local Port
while read port; do
reQ=$(echo ${port}|awk '{print $1}')
Port=$(echo {$port} | awk '{print $9}' | awk -F ":" '{print $2}')
[[ $(echo -e $NOREPEAT|grep -w "$Port") ]] && continue
NOREPEAT+="$Port\n"
case ${reQ} in

dropbear)
[[ -z $DPB ]] && local DPB=""
DPB+="$Port ";;

esac
done <<< "${portasVAR}"


[[ ! -z $DPB ]] && echo -e $DPB

local port_dropbear="$DPB"
#cat /var/log/auth.log|grep "$(date|cut -d' ' -f2,3)" > /var/log/authday.log
cat /var/log/auth.log|tail -1000 > /var/log/authday.log
local log=/var/log/authday.log
local loginsukses='Password auth succeeded'
[[ -z $port_dropbear ]] && return 1
for port in `echo $port_dropbear`; do
 for pidx in $(ps ax |grep dropbear |grep "$port" |awk -F" " '{print $1}'); do
  pids="${pids}$pidx\n"
 done
done
for pid in `echo -e "$pids"`; do
  pidlogs=`grep $pid $log |grep "$loginsukses" |awk -F" " '{print $3}'`
  i=0
    for pidend in $pidlogs; do
    let i++
    done
    if [[ $pidend ]]; then
    login=$(grep $pid $log |grep "$pidend" |grep "$loginsukses")
    PID=$pid
    user=`echo $login |awk -F" " '{print $10}' | sed -r "s/'//g"`
    waktu=$(echo $login |awk -F" " '{print $2"-"$1,$3}')
    [[ -z $user ]] && continue
	echo "$user|$PID|$waktu"
    fi
done
}
openvpn_pids () {
#nome|#loguin|#rcv|#snd|#time
  byte () {
   while read B dummy; do
   [[ "$B" -lt 1024 ]] && echo "${B} bytes" && break
   KB=$(((B+512)/1024))
   [[ "$KB" -lt 1024 ]] && echo "${KB} Kb" && break
   MB=$(((KB+512)/1024))
   [[ "$MB" -lt 1024 ]] && echo "${MB} Mb" && break
   GB=$(((MB+512)/1024))
   [[ "$GB" -lt 1024 ]] && echo "${GB} Gb" && break
   echo $(((GB+512)/1024)) terabytes
   done
   }
for user in $(mostrar_usuarios); do
user="$(echo $user|sed -e 's/[^a-z0-9 -]//ig')"
[[ ! $(sed -n "/^${user},/p" /etc/openvpn/openvpn-status.log) ]] && continue
i=0
unset RECIVED; unset SEND; unset HOUR
 while read line; do
 IDLOCAL=$(echo ${line}|cut -d',' -f2)
 RECIVED+="$(echo ${line}|cut -d',' -f3)+"
 SEND+="$(echo ${line}|cut -d',' -f4)+"
 DATESEC=$(date +%s --date="$(echo ${line}|cut -d',' -f5|cut -d' ' -f1,2,3,4)")
 TIMEON="$(($(date +%s)-${DATESEC}))"
  MIN=$(($TIMEON/60)) && SEC=$(($TIMEON-$MIN*60)) && HOR=$(($MIN/60)) && MIN=$(($MIN-$HOR*60))
  HOUR+="${HOR}h:${MIN}m:${SEC}s\n"
  let i++
 done <<< "$(sed -n "/^${user},/p" /etc/openvpn/openvpn-status.log)"
RECIVED=$(echo $(echo ${RECIVED}0|bc)|byte)
SEND=$(echo $(echo ${SEND}0|bc)|byte)
HOUR=$(echo -e $HOUR|sort -n|tail -1)
echo -e "$user|$i|$RECIVED|$SEND|$HOUR" 
done
}
err_fun () {
     case $1 in
     1)msg -verm "$(fun_trans "Usuario Nulo")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     2)msg -verm "$(fun_trans "Usuario con nombre muy corto")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     3)msg -verm "$(fun_trans "Usuario con nombre muy grande")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     4)msg -verm "$(fun_trans "Contraseña Nula")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     5)msg -verm "$(fun_trans "Contraseña muy corta")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     6)msg -verm "$(fun_trans "Contraseña muy grande")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     7)msg -verm "$(fun_trans "Duracion Nula")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     8)msg -verm "$(fun_trans "Duracion invalida utilize numeros")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     9)msg -verm "$(fun_trans "Duracion maxima y de un año")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     11)msg -verm "$(fun_trans "Limite Nulo")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     12)msg -verm "$(fun_trans "Limite invalido utilize numeros")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     13)msg -verm "$(fun_trans "Limite maximo de 999")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     14)msg -verm "$(fun_trans "Usuario Ya Existe")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;;
     esac
}
new_user () {
clear 
clear
msg -bar
usuarios_ativos=($(mostrar_usuarios))
if [[ -z ${usuarios_ativos[@]} ]]; then
msg -tit
msg -ama "   AGREGAR USUARIO | Ningun Usuario Registrado"
msg -bar
else
msg -tit
msg -ama "  AGREGAR USUARIO | Usuarios  Activos en Servidor"
msg -bar
for us in $(echo ${usuarios_ativos[@]}); do
msg -ne "  >> Usuario: " && echo "${us}"
done
msg -bar
fi
while true; do
     msg -ne "$(fun_trans "Nombre Del Nuevo Usuario")"
     read -p ": " nomeuser
     nomeuser="$(echo $nomeuser|sed -e 's/[^a-z0-9 -]//ig')"
     if [[ -z $nomeuser ]]; then
     err_fun 1 && continue
     elif [[ "${#nomeuser}" -lt "4" ]]; then
     err_fun 2 && continue
     elif [[ "${#nomeuser}" -gt "24" ]]; then
     err_fun 3 && continue
     elif [[ "$(echo ${usuarios_ativos[@]}|grep -w "$nomeuser")" ]]; then
     err_fun 14 && continue
     fi
     break
done
while true; do
     msg -ne "$(fun_trans "Contraseña Del Nuevo Usuario")"
     read -p ": " senhauser
     if [[ -z $senhauser ]]; then
     err_fun 4 && continue
     elif [[ "${#senhauser}" -lt "6" ]]; then
     err_fun 5 && continue
     elif [[ "${#senhauser}" -gt "20" ]]; then
     err_fun 6 && continue
     fi
     break
done
while true; do
     msg -ne "$(fun_trans "Tiempo de Duracion del Nuevo Usuario")"
     read -p ": " diasuser
     if [[ -z "$diasuser" ]]; then
     err_fun 7 && continue
     elif [[ "$diasuser" != +([0-9]) ]]; then
     err_fun 8 && continue
     elif [[ "$diasuser" -gt "360" ]]; then
     err_fun 9 && continue
     fi 
     break
done
while true; do
     msg -ne "$(fun_trans "Limite de Conexiones del Nuevo Usuario")"
     read -p ": " limiteuser
     if [[ -z "$limiteuser" ]]; then
     err_fun 11 && continue
     elif [[ "$limiteuser" != +([0-9]) ]]; then
     err_fun 12 && continue
     elif [[ "$limiteuser" -gt "999" ]]; then
     err_fun 13 && continue
     fi
     break
done
     tput cuu1 && tput dl1
     tput cuu1 && tput dl1
     tput cuu1 && tput dl1
     tput cuu1 && tput dl1
     msg -ne "$(fun_trans "  >> IP del Servidor"): " && echo -e "$(meu_ip)"
     msg -ne "$(fun_trans "  >> Usuario"): " && echo -e "$nomeuser"
     msg -ne "$(fun_trans "  >> Contraseña"): " && echo -e "$senhauser"
     msg -ne "$(fun_trans "  >> Dias de Duracion"): " && echo -e "$diasuser"
     msg -ne "$(fun_trans "  >> Fecha de Expiracion"): " && echo -e "$(date "+%F" -d " + $diasuser days")"
     msg -ne "$(fun_trans "  >> Limite de Conexion"): " && echo -e "$limiteuser"
msg -bar
diasuser2="$(echo "$diasuser"|bc)+1"
echo "${diasuser2}"|bc > /etc/VPS-MX/controlador/DIAS.log
diasuser3="$(less /etc/VPS-MX/controlador/DIAS.log)"
add_user "${nomeuser}" "${senhauser}" "${diasuser3}" "${limiteuser}" && msg -ama "$(fun_trans "            Usuario Creado con Exito")" || msg -verm "$(fun_trans "         Error, Usuario no creado")"
[[ $(dpkg --get-selections|grep -w "openvpn"|head -1) ]] && [[ -e /etc/openvpn/openvpn-status.log ]] && newclient "$nomeuser" "$senhauser"
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}

remove_user () {
clear
clear
msg -bar
usuarios_ativos=($(mostrar_usuarios))
if [[ -z ${usuarios_ativos[@]} ]]; then
msg -tit
msg -verm "$(fun_trans " BORAR USUARIO | Ningun usuario registrado")"
msg -bar
return 1
else
msg -tit
msg -ama "$(fun_trans " BORAR USUARIO |  Usuarios Activos del Servidor")"
msg -bar
i=0
for us in $(echo ${usuarios_ativos[@]}); do
msg -ne "[$i] ->" && echo -e "\033[1;33m ${us}"
let i++
done
msg -bar
fi
msg -ama "$(fun_trans "Escriba o Seleccione un Usuario")"
msg -bar
msg -ama "\033[1;31mSe recomienda desbloquear todas las cuentas \nbloqueadas antes de borrar algun usuario."
msg -bar
unset selection
while [[ -z ${selection} ]]; do
echo -ne "\033[1;37m$(fun_trans "Seleccione Una Opcion"): " && read selection
tput cuu1 && tput dl1
done
if [[ ! $(echo "${selection}" | egrep '[^0-9]') ]]; then
usuario_del="${usuarios_ativos[$selection]}"
else
usuario_del="$selection"
fi
[[ -z $usuario_del ]] && {
     msg -verm "$(fun_trans "Error, Usuario Invalido")"
     msg -bar
     return 1
     }
[[ ! $(echo ${usuarios_ativos[@]}|grep -w "$usuario_del") ]] && {
     msg -verm "$(fun_trans "Error, Usuario Invalido")"
     msg -bar
     return 1
     }
msg -ne "$(fun_trans "Usuario Seleccionado"): " && echo -ne "$usuario_del" 
pkill -u $usuario_del
droplim=`dropbear_pids|grep -w "$usuario_del"|cut -d'|' -f2` 
kill -9 $droplim &>/dev/null
# droplim=`droppids|grep -w "$usuario_del"|cut -d'|' -f2` 
# kill -9 $droplim &>/dev/null
rm_user "$usuario_del" && msg -verd " [$(fun_trans "Removido")]" || msg -verm " [$(fun_trans "No Removido")]"
rm -rf /etc/VPS-MX/VPS-MX-userlock
rm -rf /etc/VPS-MX/controlador/Limiter.log
unlockall2
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}
renew_user () {
clear
clear
msg -bar
usuarios_ativos=($(mostrar_usuarios))
if [[ -z ${usuarios_ativos[@]} ]]; then
msg -tit
msg -verm "$(fun_trans " EDITAR USUARIO | Ningun usuario registrado")"
msg -bar
return 1
else
msg -tit
msg -ama "$(fun_trans " EDITAR USUARIO | Usuarios Activos en el Servidor")"
msg -bar
i=0
for us in $(echo ${usuarios_ativos[@]}); do
msg -ne "[$i] ->" && echo -e "\033[1;33m ${us}"
let i++
done
msg -bar
fi
msg -ama "$(fun_trans "Escriba o seleccione un Usuario")"
msg -bar
unset selection
while [[ -z ${selection} ]]; do
echo -ne "\033[1;37m$(fun_trans "Seleccione una Opcion"): " && read selection
tput cuu1
tput dl1
done
if [[ ! $(echo "${selection}" | egrep '[^0-9]') ]]; then
useredit="${usuarios_ativos[$selection]}"
else
useredit="$selection"
fi
[[ -z $useredit ]] && {
     msg -verm "$(fun_trans "Error, Usuario Invalido")"
     msg -bar
     return 1
     }
[[ ! $(echo ${usuarios_ativos[@]}|grep -w "$useredit") ]] && {
     msg -verm "$(fun_trans "Error, Usuario Invalido")"
     msg -bar
     return 1
     }
while true; do
     msg -ne "Nuevo Tiempo de Duracion de:\033[1;33m $useredit"
     read -p ": " diasuser
     if [[ -z "$diasuser" ]]; then
     echo -e '\n\n\n'
     err_fun 7 && continue
     elif [[ "$diasuser" != +([0-9]) ]]; then
     echo -e '\n\n\n'
     err_fun 8 && continue
     elif [[ "$diasuser" -gt "360" ]]; then
     echo -e '\n\n\n'
     err_fun 9 && continue
     fi
     break
done
msg -bar
renew_user_fun "${useredit}" "${diasuser}" && msg -ama "$(fun_trans "Usuario Modificado Con Exito")" || msg -verm "$(fun_trans "Error, Usuario no Modificado")"
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}
edit_user () {
clear
clear
msg -bar
usuarios_ativos=($(mostrar_usuarios))
if [[ -z ${usuarios_ativos[@]} ]]; then
msg -tit
msg -verm "$(fun_trans " EDITTAR USER | Ningun usuario registrado")"
msg -bar
return 1
else
msg -tit
msg -ama "$(fun_trans " EDITTAR USER | Usuarios Activos del Servidor")"
msg -bar
i=0
for us in $(echo ${usuarios_ativos[@]}); do
msg -ne "[$i] ->" && echo -e "\033[1;33m ${us}"
let i++
done
msg -bar
fi
msg -ama "$(fun_trans "Escriba o seleccione un Usuario")"
msg -bar
unset selection
while [[ -z ${selection} ]]; do
echo -ne "\033[1;37m$(fun_trans "Seleccione una Opcion"): " && read selection
tput cuu1; tput dl1
done
if [[ ! $(echo "${selection}" | egrep '[^0-9]') ]]; then
useredit="${usuarios_ativos[$selection]}"
else
useredit="$selection"
fi
[[ -z $useredit ]] && {
     msg -verm "$(fun_trans "Error, Usuario Invalido")"
     msg -bar
     return 1
     }
[[ ! $(echo ${usuarios_ativos[@]}|grep -w "$useredit") ]] && {
     msg -verm "$(fun_trans "Error, Usuario Invalido")"
     msg -bar
     return 1
     }
while true; do
msg -ne "$(fun_trans "Usuario Seleccionado"): " && echo -e "$useredit"
     msg -ne "Nueva Contraseña de:\033[1;33m $useredit"
     read -p ": " senhauser
     if [[ -z "$senhauser" ]]; then
     err_fun 4 && continue
     elif [[ "${#senhauser}" -lt "6" ]]; then
     err_fun 5 && continue
     elif [[ "${#senhauser}" -gt "20" ]]; then
     err_fun 6 && continue
     fi
     break
done
while true; do
     msg -ne "Dias de Duracion de:\033[1;33m $useredit"
     read -p ": " diasuser
     if [[ -z "$diasuser" ]]; then
     err_fun 7 && continue
     elif [[ "$diasuser" != +([0-9]) ]]; then
     err_fun 8 && continue
     elif [[ "$diasuser" -gt "360" ]]; then
     err_fun 9 && continue
     fi
     break
done
while true; do
     msg -ne "Nuevo Limite de Conexion de:\033[1;33m $useredit"
     read -p ": " limiteuser
     if [[ -z "$limiteuser" ]]; then
     err_fun 11 && continue
     elif [[ "$limiteuser" != +([0-9]) ]]; then
     err_fun 12 && continue
     elif [[ "$limiteuser" -gt "999" ]]; then
     err_fun 13 && continue
     fi
     break
done
     tput cuu1 && tput dl1
     tput cuu1 && tput dl1
     tput cuu1 && tput dl1
     tput cuu1 && tput dl1
     msg -ne "$(fun_trans " >> Usuario"): " && echo -e "$useredit"
     msg -ne "$(fun_trans " >> Contraseña"): " && echo -e "$senhauser"
     msg -ne "$(fun_trans " >> Dias de Duracion"): " && echo -e "$diasuser"
     msg -ne "$(fun_trans " >> Fecha de Expiracion"): " && echo -e "$(date "+%F" -d " + $diasuser days")"
     msg -ne "$(fun_trans " >> Limite de Conexion"): " && echo -e "$limiteuser"
msg -bar
edit_user_fun "${useredit}" "${senhauser}" "${diasuser}" "${limiteuser}" && msg -ama "$(fun_trans "Usuario Modificado Con Exito")" && rm -rf ${SCPusr}/Limiter.log || msg -verm "$(fun_trans "Error, Usuario nao Modificado")"
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}
detail_user () {
clear
clear
msg -bar2
msg -tit
msg -ama "$(fun_trans "        INFORMACION DE USUARIOS REGISTRADOS ")"
msg -bar2
red=$(tput setaf 1)
gren=$(tput setaf 2)
yellow=$(tput setaf 3)
if [[ ! -e "${USRdatabase}" ]]; then
msg -verm "$(fun_trans "No se ha identificado una base de datos con los Usuarios")"
msg -verm "$(fun_trans "Los Usuarios a Seguir No contiene Ninguna Informacion")"
msg -bar2
fi
txtvar=$(printf '%-15s' "USUARIO")
txtvar+=$(printf '%-20s' "CONTRASEÑA")
txtvar+=$(printf '%-13s' "FECHA")
txtvar+=$(printf '%-10s' "LIMITE")
echo -e "\033[1;33m${txtvar}"
msg -bar2
VPSsec=$(date +%s)
while read user; do
unset txtvar
data_user=$(chage -l "$user" |grep -i co |awk -F ":" '{print $2}')
txtvar=$(printf '%-21s' "${yellow}$user")
if [[ -e "${USRdatabase}" ]]; then
  if [[ $(cat ${USRdatabase}|grep -w "${user}") ]]; then
    txtvar+="$(printf '%-21s' "${yellow}$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f2)")"
    DateExp="$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f3)"
    DataSec=$(date +%s --date="$DateExp")
    if [[ "$VPSsec" -gt "$DataSec" ]]; then    
    EXPTIME="${red}[Exp]"
    else
    EXPTIME="${gren}[$(($(($DataSec - $VPSsec)) / 86400))]"
    fi
    txtvar+="$(printf '%-29s' "${yellow}${DateExp}${EXPTIME}")"
    txtvar+="$(printf '%-5s' "${yellow}$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f4)")"
    else
    txtvar+="$(printf '%-21s' "${red}???")"
    txtvar+="$(printf '%-29s' "${red}???")"
    txtvar+="$(printf '%-11s' "${red}???")"
  fi
fi
echo -e "$txtvar"
done <<< "$(mostrar_usuarios)"
msg -bar2
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}
monit_user () {
clear
clear
msg -bar
yellow=$(tput setaf 3)
gren=$(tput setaf 2)
msg -tit
echo -e "$(fun_trans "\e[93m   MONITOR DE CONEXIONES SSH/DROPBEAR/SSL/OPENVPN")"
msg -bar
txtvar=$(printf '%-20s' " USUARIO")
txtvar+=$(printf '%-19s' "CONEXIONES")
txtvar+=$(printf '%-16s' "TIME/ON")
echo -e "\033[1;92m${txtvar}"
msg -bar
while read user; do
 _=$(
PID="0+"
[[ $(dpkg --get-selections|grep -w "openssh"|head -1) ]] && PID+="$(ps aux|grep -v grep|grep sshd|grep -w "$user"|grep -v root|wc -l)+"
[[ $(dpkg --get-selections|grep -w "dropbear"|head -1) ]] && PID+="$(dropbear_pids|grep -w "${user}"|wc -l)+"
[[ $(dpkg --get-selections|grep -w "openvpn"|head -1) ]] && [[ -e /etc/openvpn/openvpn-status.log ]] && [[ $(openvpn_pids|grep -w "$user"|cut -d'|' -f2) ]] && PID+="$(openvpn_pids|grep -w "$user"|cut -d'|' -f2)+"
PID+="0"
TIMEON="${TIMEUS[$user]}"
[[ -z $TIMEON ]] && TIMEON=0
MIN=$(($TIMEON/60))
SEC=$(($TIMEON-$MIN*60))
HOR=$(($MIN/60))
MIN=$(($MIN-$HOR*60))
HOUR="${HOR}h:${MIN}m:${SEC}s"
[[ -z $(cat ${USRdatabase}|grep -w "${user}") ]] && MAXUSER="?" || MAXUSER="$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f4)"
[[ $(echo $PID|bc) -gt 0 ]] && user="$user [\033[1;32m ON \033[0m${yellow}]" || user="$user [\033[1;31m OFF \033[0m${yellow}]"
TOTALPID="$(echo $PID|bc)/$MAXUSER"
 while [[ ${#user} -lt 45 ]]; do
 user=$user" "
 done
 while [[ ${#TOTALPID} -lt 13 ]]; do
 TOTALPID=$TOTALPID" "
 done
 while [[ ${#HOUR} -lt 8 ]]; do
 HOUR=$HOUR" "
 done
echo -e "${yellow}$user $TOTALPID $HOUR" >&2
) &
pid=$!
sleep 0.5s
done <<< "$(mostrar_usuarios)"
while [[ -d /proc/$pid ]]; do
sleep 3s
done
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}
rm_vencidos () {
clear
clear
msg -bar
msg -tit
echo -e "$(fun_trans "\e[93m           BORRANDO USUARIOS VENCIDOS ")"
msg -bar
red=$(tput setaf 1)
gren=$(tput setaf 2)
yellow=$(tput setaf 3)
txtvar=$(printf '%-25s' " USUARIO")
txtvar+=$(printf '%-25s' " VALIDIDEZ")
echo -e "\033[1;92m${txtvar}"
msg -bar
expired="${red}$(fun_trans "Usuario Expirado")"
valid="${gren}$(fun_trans "   Usuario Vigente")"
never="${yellow}$(fun_trans "Usuario Ilimitado")"
removido="${red}$(fun_trans "Eliminado")"
DataVPS=$(date +%s)
while read user; do
DataUser=$(chage -l "${user}" |grep -i co|awk -F ":" '{print $2}')
usr=$user
 while [[ ${#usr} -lt 20 ]]; do
 usr=$usr" "
 done
[[ "$DataUser" = " never" ]] && {
   echo -e "${yellow}$usr $never"
   continue
   }
DataSEC=$(date +%s --date="$DataUser")
if [[ "$DataSEC" -lt "$DataVPS" ]]; then
echo -ne "${yellow}$usr $expired"
rm_user "$user" && echo -e "($removido)"
else
echo -e "${yellow}$usr $valid"
fi
done <<< "$(mostrar_usuarios)"
rm -rf /etc/VPS-MX/VPS-MX-userlock
rm -rf /etc/VPS-MX/controlador/Limiter.log
unlockall2
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}
verif_fun () {
 # DECLARANDO VARIAVEIS PRIMARIAS
    local conexao
    local limite
    local TIMEUS
    declare -A conexao
    declare -A limite
    declare -A TIMEUS
    local LIMITERLOG="${SCPusr}/Limiter.log"
	local LIMITERLOG2="${SCPusr}/Limiter2.log"
    [[ $(dpkg --get-selections|grep -w "openssh"|head -1) ]] && local SSH=ON || local SSH=OFF
    [[ $(dpkg --get-selections|grep -w "dropbear"|head -1) ]] && local DROP=ON || local DROP=OFF
    [[ $(dpkg --get-selections|grep -w "openvpn"|head -1) ]] && [[ -e /etc/openvpn/openvpn-status.log ]] && local OPEN=ON || local OPEN=OFF
    while true; do
    unset EXPIRED
    unset ONLINES
	unset BLOQUEADO
    #[[ -e ${MyTIME} ]] && source ${MyTIME}
    local TimeNOW=$(date +%s)
    # INICIA VERIFICAȃO
    while read user; do
           echo -ne "\033[1;33mUSUARIO: \033[1;32m$user "
           if [[ ! $(echo $(mostrar_usuarios)|grep -w "$user") ]]; then
              echo -e "\033[1;31mNO EXISTE"
              continue
           fi
           local DataUser=$(chage -l "${user}" |grep -i co|awk -F ":" '{print $2}')
           if [[ ! -z "$(echo $DataUser|grep never)" ]]; then
               echo -e "\033[1;31mILIMITADO" 
               continue
           fi
           local DataSEC=$(date +%s --date="$DataUser")
           if [[ "$DataSEC" -lt "$TimeNOW" ]]; then
              EXPIRED="1+"          
              block_userfun $user -loked && echo " $user (EXPIRADO) $(date +%r--%d/%m/%y)" >> $LIMITERLOG && echo " $user (EXPIRADO) $(date +%r--%d/%m/%y)" >> $LIMITERLOG2 && KEY="862633455:AAGJ9BBJanzV6yYwLSemNAZAVwn7EyjrtcY"
URL="https://api.telegram.org/bot$KEY/sendMessage"
MSG="⚠️ AVISO DE VPS: $NOM1 ⚠️
🔹 CUENTA: $user 
❗️ 📵 EXPIRADA 📵 ❗️"
curl -s --max-time 10 -d "chat_id=$IDB1&disable_web_page_preview=1&text=$MSG" $URL && pkill -u $user
              echo -e "\033[1;31m EXPIRADO"
              continue
           fi
           local PID="0+"
           [[ $SSH = ON  ]] && PID+="$(ps aux|grep -v grep|grep sshd|grep -w "$user"|grep -v root|wc -l 2>/dev/null)+"
           [[ $DROP = ON  ]] && PID+="$(dropbear_pids|grep -w "$user"|wc -l 2>/dev/null)+"
           [[ $OPEN = ON  ]] && [[ $(openvpn_pids|grep -w "$user"|cut -d'|' -f2) ]] && PID+="$(openvpn_pids|grep -w "$user"|cut -d'|' -f2)+"
            local ONLINES+="$(echo ${PID}0|bc)+"
            local conexao[$user]="$(echo ${PID}0|bc)"
           if [[ ${conexao[$user]} -gt '0' ]]; then #CONTADOR DE TEMPO ONLINE
              [[ -z "${TIMEUS[$user]}" ]] && local TIMEUS[$user]=0
              [[ "${TIMEUS[$user]}" != +([0-9]) ]] && local TIMEUS[$user]=0
              local TIMEUS[$user]="$((300+${TIMEUS[$user]}))"
              local VARS="$(cat ${MyTIME}|grep -w -v "$user")"
              echo "TIMEUS[$user]='${TIMEUS[$user]}'" > ${MyTIME}
             for variavel in $(echo ${VARS}); do echo "${variavel}" >> ${MyTIME}; done
            fi           
           local limite[$user]="$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f4)"
           [[ -z "${limite[$user]}" ]] && continue
           [[ "${limite[$user]}" != +([0-9]) ]] && continue
           if [[ "${conexao[$user]}" -gt "${limite[$user]}" ]]; then
           local lock=$(block_userfun $user -loked)
           pkill -u $user
		   
		   droplim=`dropbear_pids|grep -w "$user"|cut -d'|' -f2` 
		   kill -9 $droplim &>/dev/null
		   
		   openlim=`openvpn_pids|grep -w "$user"|cut -d'|' -f2`
		   kill -9 $openlim &>/dev/null
		   
		   echo "$lock" >> $LIMITERLOG && echo "$lock" >> $LIMITERLOG2
           echo -e "\033[1;31m ULTRAPASO LIMITE"
           continue
           fi
           echo -e "\033[1;33m OK! \033[1;31m${conexao[$user]} CONEXIONESS"
		   BLOQUEADO="$(wc -l /etc/VPS-MX/VPS-MX-userlock | awk '{print $1}')"
		   #BLOQUEADO="$(grep -c BLOCK-MULTILOGIN /etc/VPS-MX/controlador/Limiter.log)"
		   BLOQUEADO2="$(echo ${BLOQUEADO}|bc)0"
		   BLOQUEADO3="/10"
		   EXPIRADO="$(grep -c EXPIRADO /etc/VPS-MX/controlador/Limiter.log)"
		   EXPIRADO2="$(echo ${EXPIRADO}|bc)0"
		   EXPIRADO3="/10"
    done <<< "$(mostrar_usuarios)"
    echo "${ONLINES}0"|bc > ${SCPdir}/USRonlines
    #echo "${EXPIRED}0"|bc > ${SCPdir}/USRexpired
	echo "${EXPIRADO2}${EXPIRADO3}"|bc > ${SCPdir}/USRexpired
	echo "${BLOQUEADO2}${BLOQUEADO3}"|bc > ${SCPdir}/USRbloqueados
	limseg="$(less /etc/VPS-MX/controlador/tiemlim.log)"
	
	sleep $limseg # TEMPO DE ESPERA DO LOOP
    clear
    done
}
SPR &
backup_fun () {
clear
clear
msg -bar
msg -tit
msg -ama "$(fun_trans "        HERRAMIENTA DE BACKUP DE USUARIOS")"
msg -bar
menu_func "CREAR BACKUP" "RESTAURAR BACKUP"
msg -bar
unset selection
while [[ ${selection} != @([1-2]) ]]; do
echo -ne "\033[1;37m$(fun_trans "Seleccione una Opcion"): " && read selection
tput cuu1 && tput dl1
done
case ${selection} in
1)
cp ${USRdatabase} $HOME/VPS-MX-Backup
msg -azu "$(fun_trans "Procedimiento Hecho con Exito, Guardado en:")"
echo ""
echo -e "\033[1;31mBACKUP > [\033[1;32m$HOME/VPS-MX-Backup\033[1;31m]"
echo ""
;;
2)
while [[ ! -e ${dirbackup} ]]; do
echo -ne "\033[1;37m ¡¡Recomiendo DESACTIVAR Limitador si es que lo tine ACTIVO!!\n"
echo -ne "\033[1;37m Escriba la ubicacion de la copia de seguridad\n" 
msg -bar
echo -ne "\033[1;37m ENTER: para ruta predeterminada /root/VPS-MX-Backup: " && read dirbackup
echo ""
echo "----------  RESTAURANDO CUENTAS ESPERE "
echo ""
msg -bar
[[ -z "${dirbackup}" ]] && dirbackup="/root/VPS-MX-Backup"
tput cuu1 && tput dl1
done
VPSsec=$(date +%s)
while read line; do
nome=$(echo ${line}|cut -d'|' -f1)
[[ $(echo $(mostrar_usuarios)|grep -w "$nome") ]] && { msg -verm "$nome [ERROR]"
  continue
  }
senha=$(echo ${line}|cut -d'|' -f2)
DateExp=$(echo ${line}|cut -d'|' -f3)
DataSec=$(date +%s --date="$DateExp")
[[ "$VPSsec" -lt "$DataSec" ]] && dias="$(($(($DataSec - $VPSsec)) / 86400))" || dias="NP"
limite=$(echo ${line}|cut -d'|' -f4)

add_user "$nome" "$senha" "$dias" "$limite" &>/dev/null && msg -verd "$nome [CUENTA VALIDA]" || msg -verm "$nome [CUENTA INVALIDA FECHA EXPIRADA]"
done < ${dirbackup}
;;
esac
echo ""
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}

##LIMITADOR 

verif_funx () {
clear
clear
msg -bar
msg -tit
echo -e "\033[1;32m             LIMITADOR DE CUENTAS"
msg -bar
echo -e "Esta Opcion Limita las Conexiones de SSH/SSL/DROPBEAR"
PIDVRF="$(ps aux|grep "${SCPusr}/usercodes verificar"|grep -v grep|awk '{print $2}')"
if [[ -z $PIDVRF ]]; then
msg -bar
echo -ne "\033[1;96m   ¿Cada cuantos segundos ejecutar el limitador?\n\033[1;97m  +Segundos = -Uso de CPU | -Segundos = +Uso de CPU\033[0;92m \n                Predeterminado:\033[1;37m 120s\n     Cuantos Segundos (Numeros Unicamente): " && read tiemlim   
[[ -z "$tiemlim" ]] && tiemlim="120"
echo "${tiemlim}" > /etc/VPS-MX/controlador/tiemlim.log
cd ${SCPusr}
screen -dmS very ${SCPusr}/usercodes verificar
else
for pid in $(echo $PIDVRF); do
kill -9 $pid &>/dev/null
done
[[ -e ${SCPdir}/USRonlines ]] && rm ${SCPdir}/USRonlines
[[ -e ${SCPdir}/USRexpired ]] && rm ${SCPdir}/USRexpired
[[ -e ${SCPdir}/USRbloqueados ]] && rm ${SCPdir}/USRbloqueados
fi
msg -bar
[[ -z ${VERY} ]] && verificar="\033[1;32m ACTIVADO " || verificar="\033[1;31m DESACTIVADO "
echo -e "            $verificar  --  CON EXITO"
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}

##DESBLOEUEAR

verif2_funx () {
clear
clear
msg -bar
msg -tit
echo -e "\033[1;32m      DESBLOQUEO AUT. Y LIMPIADOR DE EXPIARDOS"
msg -bar
echo -e "Esta opcion desbloquea cada 60 segundos a usuarios\nbloqueados por el limitador y limpia los usuarios expirados"
PIDVRF2="$(ps aux|grep "${SCPusr}/usercodes desbloqueo"|grep -v grep|awk '{print $2}')"
if [[ -z $PIDVRF2 ]]; then
msg -bar
echo -ne "\033[1;96m   ¿Cada cuantos segundos ejecutar el desbloqueador?\n\033[1;97m  +Segundos = -Uso de CPU | -Segundos = +Uso de CPU\033[0;92m \n                Predeterminado:\033[1;37m 300s\n     Cuantos Segundos (Numeros Unicamente): " && read tiemdes   
[[ -z "$tiemdes" ]] && tiemdes="300"
echo "${tiemdes}" > /etc/VPS-MX/controlador/tiemdes.log
cd ${SCPusr} 
screen -dmS very2 ${SCPusr}/usercodes desbloqueo
else
for pid in $(echo $PIDVRF2); do
kill -9 $pid &>/dev/null
done

fi
msg -bar
[[ -z ${VERY2} ]] && desbloqueo="\033[1;32m ACTIVADO " || desbloqueo="\033[1;31m DESACTIVADO "
echo -e "            $desbloqueo  --  CON EXITO"
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}

baner_fun () {
banner_on () {
clear 
clear 
local="/etc/VPS-MX/bannerssh"
rm -rf $local  > /dev/null 2>&1
local2="/etc/dropbear/banner"
chk=$(cat /etc/ssh/sshd_config | grep Banner)
if [ "$(echo "$chk" | grep -v "#Banner" | grep Banner)" != "" ]; then
local=$(echo "$chk" |grep -v "#Banner" | grep Banner | awk '{print $2}')
 else
echo "" >> /etc/ssh/sshd_config
echo "Banner /etc/VPS-MX/bannerssh" >> /etc/ssh/sshd_config
local="/etc/VPS-MX/bannerssh"
fi
msg -bar
msg -tit
msg -ama "         AGREGAR BANNER SSH/SSL/DROPBEAR"
msg -bar
msg -ne "$(fun_trans  "Inserte el BANNER de preferencia en HTML sin saltos"): \n\n" && read ban_ner
echo ""
msg -bar
credi="$(less /etc/VPS-MX/message.txt)"
echo "$ban_ner" >> $local
echo '<p style="text-align: center;"><span style="color: #0000ff;"><strong>'$credi'</strong></span><br /><em><span style="color: #ff0000;"><strong>SCRIPT - VPS&bull;MX</strong></span></em></p>' >> $local
if [[ -e "$local2" ]]; then
rm $local2  > /dev/null 2>&1
cp $local $local2 > /dev/null 2>&1
fi 
msg -verd "$(fun_trans  "           BANNER AGREGADO CON !! EXITO ¡¡" )" && msg -bar
service dropbear stop 2>/dev/null
service ssh restart 2>/dev/null
service dropbear restart 2>/dev/null
}

banner_off () {
clear
clear
msg -bar
msg -tit
msg -ama "         ELIMINANDO  BANNER SSH/SSL/DROPBEAR"
msg -bar
sed -i '/'Banner'/d' /etc/ssh/sshd_config
sed -i -e 's/^[ \t]*//; s/[ \t]*$//; /^$/d' /etc/ssh/sshd_config
echo "" >> /etc/ssh/sshd_config
rm -rf  /etc/dropbear/banner > /dev/null 2>&1
echo "" > /etc/dropbear/banner  > /dev/null 2>&1
service dropbear stop 2>/dev/null
service ssh restart 2>/dev/null
service dropbear restart 2>/dev/null
echo -e "\033[1;92m            BANNER ELIMINADO !! EXITO ¡¡ "
msg -bar
}
clear
clear
msg -bar
msg -tit
msg -ama "         AGREGAR BANNER SSH/SSL/DROPBEAR"
msg -bar
echo -e "${cor[1]}            Escoja la opcion deseada."
msg -bar
echo -e "\033[1;92m 1).- \033[1;37m AGREGAR BANNER SSH/SSL/DROPBEAR "
echo -e "\033[1;92m 2).- \033[1;37m ELIMINAR Y DESACTIVAR BANNER   "
msg -bar
echo -ne "\033[1;37mDigite solo el numero segun su respuesta: \033[1;32m"
read opcao
case $opcao in
1)
msg -bar
banner_on
;;
2)
msg -bar
banner_off
;;
esac
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}

desbloqueo_auto () {
while true; do
Desbloqueo.sh 2>/dev/null
tiemdes="$(less /etc/VPS-MX/controlador/tiemdes.log)"
sleep $tiemdes
    done
}

rec_total () {
clear
clear
msg -bar
msg -tit
echo -e "\033[1;32m  REGISTRO TOTAL DE CUENTAS VIEJAS Y NUEVAS"
msg -bar
cat /etc/VPS-MX/VPS-MXuser
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
}
# LIMITADOR AUTO
if [[ "$1" = "verificar" ]]; then
verif_fun
exit
fi
[[ -z ${VERY} ]] && verificar="\033[1;31m[DESACTIVADO]" || verificar="\033[1;32m[ACTIVO]"

# DESBLOQUEO AUTO
if [[ "$1" = "desbloqueo" ]]; then
desbloqueo_auto
exit
fi
[[ -z ${VERY2} ]] && desbloqueo="\033[1;31m[DESACTIVADO]" || desbloqueo="\033[1;32m[ACTIVO]"
msg -tit
msg -ama "  MENU ADMINISTRACION DE USUARIOS SSL/SSH/DROPBEAR"
msg -bar
msg -bar3
menu_func "CREAR NUEVO USUARIO" "CREAR USUARIO TEMPORAL" "REMOVER USUARIO" "BLOQUEAR O DESBLOQUEAR USUARIO" "REINICIAR CONTADOR DE BLOQUEADOS y EXPIRADOS" "EDITAR USUARIO" "RENOVAR USUARIO" "DETALLES DE TODOS USUARIOS" "MONITOR DE USUARIOS CONECTADOS" "ELIMINAR USUARIOS VENCIDOS" "BACKUP USUARIOS" "AGREGAR/ELIMINAR BANNER " "\033[1;31m⚠️ELIMINAR TODOS LOS USUARIOS⚠️ \n" " -fi ${verificar} \033[1;97m🔒 LIMITADOR-DE-CUENTAS 🔒 -" " -fi ${desbloqueo} \033[1;97m🔓 DESBLOQUEO-AUTOMATICO 🔓 -" "\033[1;92mLOG DE CUENTAS REGISTRADAS" "LIMPIAR LOG DE LIMITADOR"
[[ -e "${SCPusr}/Limiter2.log" ]] && echo -ne "$(msg -verd "  [18]") $(msg -verm2 "==>") " &&  msg -azu "$(fun_trans "\033[1;93mVER LOG DE LIMITADOR")" 
echo -ne ""$(msg -bar)"   \n$(msg -verd "  [0]") $(msg -verm2 "==>")" &&  msg -bra  "  \e[97m\033[1;41m VOLVER \033[1;37m"
msg -bar
selection=$(selection_fun 18)
case ${selection} in
1)new_user;;
2)${SCPdir2}/Crear-Demo.sh "${idioma}";;
3)remove_user;;
4)block_user;;
5)reset_contador;;
6)edit_user;;
7)renew_user;;
8)detail_user;;
9)monit_user;;
10)rm_vencidos;;
11)backup_fun;;
12)baner_fun;;
13)eliminar_all;;
14)verif_funx;;
15)verif2_funx;;
16)rec_total;;
17)
rm -rf ${SCPusr}/Limiter2.log
echo -e "\033[1;32m  LOG ELIMINADO CON EXITO"
msg -bar
msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
;;
18)
clear 
clear
msg -bar
sed -i -e 's/^[ \t]*//; s/[ \t]*$//; /^$/d' /etc/VPS-MX/controlador/Limiter2.log
[[ -e "${SCPusr}/Limiter2.log" ]] && {
msg -tit
msg -ama "              REGISTRO DEL LIMITADOR "
 cat ${SCPusr}/Limiter2.log
 msg -bar
 }
 msg -ne " Enter Para Continuar" && read enter
${SCPusr}/usercodes
;;
esac
