#!/bin/bash
# -*- ENCODING: UTF-8 -*-
rm -rf instalscript.sh &>/dev/null
module="/etc/ADMRufu/module"
[[ ! -e ${module} ]] && exit
source ${module}

export _hora=$(printf '%(%H:%M:%S)T') 
export _fecha=$(printf '%(%D)T')

export ADMRufu="/etc/ADMRufu" && [[ ! -d ${ADMRufu} ]] && mkdir ${ADMRufu}
export ADM_inst="${ADMRufu}/install" && [[ ! -d ${ADM_inst} ]] && mkdir ${ADM_inst}
export ADM_src="${ADMRufu}/source" && [[ ! -d ${ADM_src} ]] && mkdir ${ADM_src}
export ADM_crt="${ADM_src}/cert" && [[ ! -d ${ADM_crt} ]] && mkdir ${ADM_crt}
export ADM_slow="${ADM_src}/slowdns" && [[ ! -d ${ADM_slow} ]] && mkdir ${ADM_slow}
export ADM_user="${ADMRufu}/user" && [[ ! -d ${ADM_user} ]] && mkdir ${ADM_user}
export ADM_tmp="${ADMRufu}/tmp" && [[ ! -d ${ADM_tmp} ]] && mkdir ${ADM_tmp}
export numero='^[0-9]+$'
export letra='^[A-Za-z]+$'
export tx_num='^[A-Za-z0-9]+$'

export v2rdir="${ADMRufu}/v2r" && [[ ! -d ${v2rdir} ]] && mkdir ${v2rdir}
export user_conf="${v2rdir}/user" && [[ ! -e $user_conf ]] && touch $user_conf
export backdir="${v2rdir}/back" && [[ ! -d ${backdir} ]] && mkdir ${backdir}
export tmpdir="$backdir/tmp"
export config="/etc/v2ray/config.json"
export temp="/etc/v2ray/temp.json"
export fstab="/etc/fstab"
export sysctl="/etc/sysctl.conf"
export swap="/swapfile"

#======cloudflare========
export _dns='2473a8a21bd6a727d7d6eed58a6751a0'
export apikey='ZN685I3ss0lEvQOr79SVYsYVDviz9GGRys_Upgu0'
export _domain='admrufu.online'
export url='https://api.cloudflare.com/client/v4/zones'
#========================

#PROCESSADOR
export _core=$(printf '%-1s' "$(grep -c cpu[0-9] /proc/stat)")
export _usop=$(printf '%-1s' "$(top -bn1 | awk '/Cpu/ { cpu = "" 100 - $8 "%" }; END { print cpu }')")

#SISTEMA-USO DA CPU-MEMORIA RAM
export ram1=$(free -h | grep -i mem | awk {'print $2'})
export ram2=$(free -h | grep -i mem | awk {'print $4'})
export ram3=$(free -h | grep -i mem | awk {'print $3'})

export _ram=$(printf ' %-9s' "$(free -h | grep -i mem | awk {'print $2'})")
export _usor=$(printf '%-8s' "$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2 }')")

if [[ ! -f ${ADM_tmp}/style ]]; then
  echo -e "infsys 1\nport 0\nresel 0\ncontador 1\nlimit 0" > ${ADM_tmp}/style
fi

if [[ ! $(id -u) = 0 ]]; then
	clear
	msg -bar
	print_center -ama "ERROR DE EJECUCION"
	msg -bar
	print_center -ama "DEVE EJECUTAR DESDE EL USUSRIO ROOT"
	echo ''
	print_center -ama 'TAMBIEN "sudo su"'
	print_center -ama 'O BIEN'
	print_center -ama '"sudo menu"'
	msg -bar
	exit
fi

if [[ ! $(cat '/etc/passwd'|grep 'root'|grep -v 'false'|awk -F ':' '{print $2}') = 'x' ]]; then
	msg -bar
	print_center -ama 'CAMBIO DE CONTRASEÑA ROOT REQUERIDO'
	msg -bar
	msg -ne " Ingrese la Nueva Contraseña: "
	read opcion
	pwconv
	(echo "$opcion" ; echo "$opcion")|passwd root &>/dev/null
	tput cuu1 && tput dl1
	print_center -verd "SE CAMBIO LA CONTRASEÑA ROOT"
	enter
fi

[[ ! -e "/var/spool/cron/crontabs/root" ]] && touch /var/spool/cron/crontabs/root

#======BODY=========

 in_opcion(){
 	msg -ne " $1: "
 	read opcion
 }

fun_trans(){ 
	local texto
	local retorno
	declare -A texto
	SCPidioma="${ADM_tmp}/idioma"
	[[ ! -e ${SCPidioma} ]] && touch ${SCPidioma}
	local LINGUAGE=$(cat ${SCPidioma})
	[[ -z $LINGUAGE ]] && LINGUAGE=es
	[[ $LINGUAGE = "es" ]] && echo "$@" && return
	[[ ! -e /usr/bin/trans ]] && wget -O /usr/bin/trans https://raw.githubusercontent.com/rudi9999/VPS-MX-8.0/master/ArchivosUtilitarios/trans &> /dev/null
	[[ ! -e ${ADM_tmp}/texto-adm ]] && touch ${ADM_tmp}/texto-adm
	source ${ADM_tmp}/texto-adm
	if [[ -z "$(echo ${texto[$@]})" ]]; then
		#ENGINES=(aspell google deepl bing spell hunspell apertium yandex)
		#NUM="$(($RANDOM%${#ENGINES[@]}))"
		retorno="$(source trans -e bing -b es:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)"
		echo "texto[$@]='$retorno'"  >> ${ADM_tmp}/texto-adm
		echo "$retorno"
	else
		echo "${texto[$@]}"
	fi
}

mine_port(){
	unset puertos
	declare -A port
	local portasVAR=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN" | grep -E 'squid|apache|dropbear|ssh|openvpn|stunnel|python|node|v2ray|badvpn-ud')
	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
			squid|squid3)
			[[ -z ${port[SQD]} ]] && local port[SQD]="\033[1;31m SQUID: \033[1;32m"
			port[SQD]+="$Port ";;
			apache|apache2)
			[[ -z ${port[APC]} ]] && local port[APC]="\033[1;31m APACHE: \033[1;32m"
			port[APC]+="$Port ";;
			ssh|sshd)
			[[ -z ${port[SSH]} ]] && local port[SSH]="\033[1;31m SSH: \033[1;32m"
			port[SSH]+="$Port ";;
			dropbear)
			[[ -z ${port[DPB]} ]] && local port[DPB]="\033[1;31m DROPBEAR: \033[1;32m"
			port[DPB]+="$Port ";;
			ssserver|ss-server)
			[[ -z ${port[SSV]} ]] && local port[SSV]="\033[1;31m SHADOWSOCKS: \033[1;32m"
			port[SSV]+="$Port ";;
			openvpn)
			[[ -z ${port[OVPN]} ]] && local port[OVPN]="\033[1;31m OPENVPN(TCP): \033[1;32m"
			port[OVPN]+="$Port ";;
			stunnel4|stunnel)
			[[ -z ${port[SSL]} ]] && local port[SSL]="\033[1;31m SSL: \033[1;32m"
			port[SSL]+="$Port ";;
			python|python3)
			[[ -z ${port[PY3]} ]] && local port[PY3]="\033[1;31m PYTHON: \033[1;32m"
			port[PY3]+="$Port ";;
			node|nodejs)
			[[ -z ${port[WS]} ]] && local port[WS]="\033[1;31m WEBSOCKET: \033[1;32m"
			port[WS]+="$Port ";;
			v2ray)
			[[ -z ${port[V2R]} ]] && local port[V2R]="\033[1;31m V2RAY: \033[1;32m"
			port[V2R]+="$Port ";;
			badvpn-ud)
			[[ -z ${port[BAD]} ]] && local port[BAD]="\033[1;31m BADVPN: \033[1;32m"
			port[BAD]+="$Port ";;
		esac
	done <<< "${portasVAR}"

	#UDP
	local portasVAR=$(lsof -V -i UDP -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND"|grep -E 'openvpn|dns-serve|v2ray')
	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
			openvpn)
			[[ -z ${port[OVPN]} ]] && local port[OVPN]="\033[1;31m OPENVPN(UDP): \033[1;32m"
			port[OVPN]+="$Port ";;
			dns-serve)
			[[ -z ${port[SLOW]} ]] && local port[SLOW]="\033[1;31m SlowDNS: \033[1;32m"
			port[SLOW]+="$Port ";;
			#v2ray)
			#[[ -z ${port[V2R]} ]] && local port[V2R]="\033[1;31m V2RAY(UDP): \033[1;32m"
			#port[V2R]+="$Port ";;
		esac
	done <<< "${portasVAR}"

	k=1

	for line in "${port[@]}"; do
		[[ -z "$line" ]] && continue
		let RESTO=k%2

		if [[ $RESTO -eq 0 ]]; then
			puertos+="$line\n"
		else
			puertos+="$line-"
		fi
		let k++

	done

	echo -e "$puertos"|column -t -s '-'

}

ofus () {
  unset server
  server=$(echo ${txt_ofuscatw}|cut -d':' -f1)
  unset txtofus
  number=$(expr length $1)
  for((i=1; i<$number+1; i++)); do
    txt[$i]=$(echo "$1" | cut -b $i)
    case ${txt[$i]} in
      ".")txt[$i]="*";;
      "*")txt[$i]=".";;
      "_")txt[$i]="@";;
      "@")txt[$i]="_";;
      #"1")txt[$i]="@";;
      #"@")txt[$i]="1";;
      #"2")txt[$i]="?";;
      #"?")txt[$i]="2";;
      #"4")txt[$i]="%";;
      #"%")txt[$i]="4";;
      "-")txt[$i]="K";;
      "K")txt[$i]="-";;
      "1")txt[$i]="f";;
      "2")txt[$i]="e";;
      "3")txt[$i]="d";;
      "4")txt[$i]="c";;
      "5")txt[$i]="b";;
      "6")txt[$i]="a";;
      "7")txt[$i]="9";;
      "8")txt[$i]="8";;
      "9")txt[$i]="7";;
      "a")txt[$i]="6";;
      "b")txt[$i]="5";;
      "c")txt[$i]="4";;
      "d")txt[$i]="3";;
      "e")txt[$i]="2";;
      "f")txt[$i]="1";;
    esac
    txtofus+="${txt[$i]}"
  done
  echo "$txtofus" | rev
}

fun_bar(){
	comando="$1"
	txt="$2"
	_=$(
	$comando > /dev/null 2>&1
	) & > /dev/null
	pid=$!
	while [[ -d /proc/$pid ]]; do
		echo -ne " \033[1;33m$txt["
		for((i=0; i<10; i++)); do
			echo -ne "\033[1;31m##"
			sleep 0.2
		done
		echo -ne "\033[1;33m]"
		sleep 1s
		echo
		tput cuu1 && tput dl1
	done
	echo -e " \033[1;33m$txt[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m"
	sleep 1s
}

fun_ip(){
  if [[ -e ${ADM_tmp}/MEUIPADM ]]; then
    echo "$(cat ${ADM_tmp}/MEUIPADM)"
  else
    MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1)
    MEU_IP2=$(wget -qO- ipv4.icanhazip.com)
    [[ "$MEU_IP" != "$MEU_IP2" ]] && IP="$MEU_IP2" && echo "$MEU_IP2" || IP="$MEU_IP" && echo "$MEU_IP"
    echo "$MEU_IP2" > ${ADM_tmp}/MEUIPADM
  fi
}

fun_eth(){
	eth=$(ifconfig | grep -v inet6 | grep -v lo | grep -v 127.0.0.1 | grep "encap:Ethernet" | awk '{print $1}')
    [[ $eth != "" ]] && {
    	msg -bar
    	msg -ama " $(fun_trans "Aplicar el sistema para mejorar los paquetes SSH?")"
    	msg -ama " $(fun_trans "Opciones para usuarios avanzados")"
    	msg -bar
    	read -p " [S/N]: " -e -i n sshsn
    	[[ "$sshsn" = @(s|S|y|Y) ]] && {
    		echo -e "${cor[1]} $(fun_trans "Correccion de problemas de paquetes en SSH ...")"
            echo -e " $(fun_trans "¿Cual es la tasa RX?")"
            echo -ne "[ 1 - 999999999 ]: "; read rx
            [[ "$rx" = "" ]] && rx="999999999"
            echo -e " $(fun_trans "¿Cual es la tasa TX?")"
            echo -ne "[ 1 - 999999999 ]: "; read tx
            [[ "$tx" = "" ]] && tx="999999999"
            apt-get install ethtool -y > /dev/null 2>&1
            ethtool -G $eth rx $rx tx $tx > /dev/null 2>&1
        }
        msg -bar
    }
}

mportas2(){
	unset portas
	portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN")
	while read port; do
		var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}')
		[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n"
	done <<< "$portas_var"
	i=1
	echo -e "$portas"
}

mportas(){
	unset portas
	portas_var=$(lsof -V -i -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND")
	while read port; do
		var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}')
		[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n"
	done <<< "$portas_var"
	i=1
	echo -e "$portas"
}


os_system(){
  system=$(echo $(cat -n /etc/issue |grep 1 |cut -d' ' -f6,7,8 |sed 's/1//' |sed 's/      //'))
  echo $system|awk '{print $1, $2}'
}

reiniciar_vps () {
  echo -ne " \033[1;31m[ ! ] Sudo Reboot"
  sleep 3s
  echo -e "\033[1;32m [OK]"
  (
    sudo reboot
    ) > /dev/null 2>&1
  msg -bar
  return
}

# Menu Ferramentas
systen_info(){
  msg -ama "$(fun_trans "DETALLES DEL SISTEMA")"
  null="\033[1;31m"
  msg -bar
  if [ ! /proc/cpuinfo ]; then msg -verm "$(fun_trans "Sistema No Soportado")" && msg -bar; return 1; fi
  if [ ! /etc/issue.net ]; then msg -verm "$(fun_trans "Sistema No Soportado")" && msg -bar; return 1; fi
  if [ ! /proc/meminfo ]; then msg -verm "$(fun_trans "Sistema No Soportado")" && msg -bar; return 1; fi
  totalram=$(free | grep Mem | awk '{print $2}')
  usedram=$(free | grep Mem | awk '{print $3}')
  freeram=$(free | grep Mem | awk '{print $4}')
  swapram=$(cat /proc/meminfo | grep SwapTotal | awk '{print $2}')
  system=$(cat /etc/issue.net)
  clock=$(lscpu | grep "CPU MHz" | awk '{print $3}')
  based=$(cat /etc/*release | grep ID_LIKE | awk -F "=" '{print $2}')
  processor=$(cat /proc/cpuinfo | grep "model name" | uniq | awk -F ":" '{print $2}')
  cpus=$(cat /proc/cpuinfo | grep processor | wc -l)
  [[ "$system" ]] && msg -ama "$(fun_trans "Sistema"): ${null}$system" || msg -ama "$(fun_trans "Sistema"): ${null}???"
  [[ "$based" ]] && msg -ama "$(fun_trans "Base"): ${null}$based" || msg -ama "$(fun_trans "Base"): ${null}???"
  [[ "$processor" ]] && msg -ama "$(fun_trans "Procesador"): ${null}$processor x$cpus" || msg -ama "$(fun_trans "Procesador"): ${null}???"
  [[ "$clock" ]] && msg -ama "$(fun_trans "Frecuencia de Operacion"): ${null}$clock MHz" || msg -ama "$(fun_trans "Frecuencia de Operacion"): ${null}???"
  msg -ama "$(fun_trans "Uso del Procesador"): ${null}$(ps aux  | awk 'BEGIN { sum = 0 }  { sum += sprintf("%f",$3) }; END { printf " " "%.2f" "%%", sum}')"
  msg -ama "$(fun_trans "Memoria Virtual Total"): ${null}$(($totalram / 1024))"
  msg -ama "$(fun_trans "Memoria Virtual En Uso"): ${null}$(($usedram / 1024))"
  msg -ama "$(fun_trans "Memoria Virtual Libre"): ${null}$(($freeram / 1024))"
  msg -ama "$(fun_trans "Memoria Virtual Swap"): ${null}$(($swapram / 1024))MB"
  msg -ama "$(fun_trans "Tempo Online"): ${null}$(uptime)"
  msg -ama "$(fun_trans "Nombre De La Maquina"): ${null}$(hostname)"
  msg -ama "$(fun_trans "IP De La  Maquina"): ${null}$(ip addr | grep inet | grep -v inet6 | grep -v "host lo" | awk '{print $2}' | awk -F "/" '{print $1}')"
  msg -ama "$(fun_trans "Version de Kernel"): ${null}$(uname -r)"
  msg -ama "$(fun_trans "Arquitectura"): ${null}$(uname -m)"
  msg -bar
  return 0
}

# Menu Instalaciones
pid_inst(){
	[[ $1 = "" ]] && echo -e "\033[1;31m[OFF]" && return 0
	unset portas
	portas_var=$(lsof -V -i -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND")
	i=0
	while read port; do
		var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}')
		[[ "$(echo -e ${portas[@]}|grep "$var1 $var2")" ]] || {
			portas[$i]="$var1 $var2\n"
			let i++
		}
	done <<< "$portas_var"
	[[ $(echo "${portas[@]}"|grep "$1") ]] && echo -e "\033[1;32m[ON]" || echo -e "\033[1;31m[OFF]"
}

info_sys(){
	#v=$(date '+%s' -d $(cat $ADMRufu/vercion)))
	info_so=$(printf '%-17s' "$(os_system)")
	info_ip=$(printf '%-18s' "$(fun_ip)")
	info_ram1=$(printf '%-7s' "${ram1}")
	info_ram2=$(printf '%-7s' "${ram2}")
	info_ram3=$(printf '%-7s' "${ram3}")
	info_fecha=$(printf '%-15s' "${_fecha}")
	info_hora=$(printf '%-15s' "${_hora}")

	systema=$(printf '%-23s' 'SISTEMA')
	systema+=$(printf '%-16s' 'MEMORIA')
	systema+='PROSESADOR'

	msg -verd " $systema"

	echo -e " $(msg -teal "S.O:") $(msg -azu "$info_so") $(msg -teal "RAM:")    $(msg -verd "$info_ram1") $(msg -teal "CPU:") $(msg -verd "$_core")"
	echo -e " $(msg -teal "IP:") $(msg -azu "$info_ip") $(msg -teal "USADA:")  $(msg -verd "$info_ram3") $(msg -teal "EN USO:")$(msg -verd "$_usop")"
	echo -e " $(msg -teal "FECHA:") $(msg -azu "$info_fecha") $(msg -teal "LIBRE:")  $(msg -verd "$info_ram2")"
	echo -e " $(msg -teal "HORA:")  $(msg -azu "$info_hora") $(msg -teal "EN USO:") $(msg -verd "$_usor")"
}

cabesera(){
	msg -bar
	print_center -azu "=====>>>> ADMRufu <<<<====="|lolcat
	msg -bar
}

droppids(){
  port_dropbear=`ps aux|grep 'dropbear'|awk NR==1|awk '{print $17;}'`

  log=/var/log/auth.log
  loginsukses='Password auth succeeded'

  pids=`ps ax|grep 'dropbear'|grep " $port_dropbear"|awk -F " " '{print $1}'`

  for pid in $pids; do
    pidlogs=`grep $pid $log |grep "$loginsukses" |awk -F" " '{print $3}'`

    i=0
    for pidend in $pidlogs; do
      let i=i+1
    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}'`
       while [ ${#waktu} -lt 13 ]; do
           waktu=$waktu" "
       done
       while [ ${#user} -lt 16 ]; do
           user=$user" "
       done
       while [ ${#PID} -lt 8 ]; do
           PID=$PID" "
       done
       echo "$user $PID $waktu"
    fi
done
}

contador(){
	users=$(cat /etc/passwd|grep 'home'|grep 'false'|grep -v 'syslog'|awk -F ':' '{print $1}')
	dpids=$(droppids)
	time=$(date +%s)
	[[ -e /etc/openvpn/openvpn-status.log ]] && ovpn_log=$(cat /etc/openvpn/openvpn-status.log)

	n='0'
	i='0'
	conect='0'
	for _user in $users; do
		[[ -z "$(ps -u $_user|grep sshd)" ]] && sqd=0 || sqd=1
		[[ -z "$(echo $ovpn_log|grep -E ,"$_user",)" ]] && ovp=0 || ovp=1
        [[ -z "$(echo $dpids|grep -w "$_user")" ]] && drop=0 || drop=1

        conex=$(($sqd + $ovp + $drop))
        [[ $conex -ne 0 ]] && let conect++

		if [[ $(chage -l $_user |grep 'Account expires' |awk -F ': ' '{print $2}') != never ]]; then
			[[ $time -gt $(date '+%s' -d "$(chage -l $_user |grep "Account expires" |awk -F ': ' '{print $2}')") ]] && let n++
		fi
		[[ $(passwd --status $_user|cut -d ' ' -f2) = "L" ]] && let i++
	done

	_onlin=$(printf '%-7s' "$conect")
	_userexp=$(printf '%-7s' "$n")
	_lok=$(printf '%-7s' "$i")
	_tuser=$(echo "$users"|sed '/^$/d'|wc -l)

	echo -e " $(msg -verd "ONLI:") $(msg -azu "$_onlin") $(msg -verm2 "EXP:") $(msg -azu "$_userexp") $(msg -teal "LOK:") $(msg -azu "$_lok") $(msg -ama "TOTAL:") $(msg -azu "$_tuser")"
}

lou(){
  source <(echo -e "$(cat /etc/bash.bashrc)\nTMOUT=1")
}

ULK_ALF(){
	title "Desactivar contraseñas Alfanumericas"
	msg -ama " Esto desactivara el uso de contraseñas Alfanumericas\n en vps de VULTR, y otros. Permitiendo usar cualquier\n combinacion de caracteres mayor a 4 digitos."
	msg -bar
	msg -ne " Continuar? [S/N]: "
	read opcion
	[[ "$opcion" != @(s|S|y|Y) ]] && return
	tput cuu1 && tput dl1
	apt-get install libpam-cracklib -y > /dev/null 2>&1
	echo -e '#
password [success=1 default=ignore] pam_unix.so obscure sha512
password requisite pam_deny.so
password required pam_permit.so' > /etc/pam.d/common-password
    chmod +x /etc/pam.d/common-password
    print_center -verd "Contraseña Alfanumerica Desactivada"
    msg -bar
    print_center -ama "►► Presione enter para continuar ◄◄"
    read
}

backup(){

	bkusr(){
    all_user=$(cat /etc/passwd|grep 'home'|grep 'false'|grep -v 'syslog')
    all_name=('' $(echo "$all_user"|awk -F ':' '{print $1}'))
		clear
		msg -bar
		if [[ -z ${all_name[@]} ]]; then
			print_center -ama "No se encontraron usuarios"
			msg -bar
			enter
			return
		fi
		print_center -ama "CREANDO COPIA DE SEGURIDAD"
		msg -bar
		sleep 2
		local userback
		for u in `echo ${all_name[@]}`; do
      dat=$(echo "$all_user"|grep -w "$u"|cut -d ':' -f5)
      Limit_mode=$(echo "$dat"|cut -d ',' -f1)
      case $Limit_mode in
        token)pass=$(cat ${ADM_user}/passwd_token);;
         hwid)pass="$u";;
            *)pass=$(echo "$dat"|cut -d ',' -f2);;
      esac
			fecha=$(chage -l "$u"|sed -n '4p'|awk -F ': ' '{print $2}')
			EXPTIME="$(($(($(date '+%s' -d "${fecha}") - $(date +%s))) / 86400))"
			stat=$(passwd --status $u|cut -d ' ' -f2)
      userback+="$u|$pass|$EXPTIME|$dat|$stat\n"
		done
		echo -e "$userback" > ${ADM_tmp}/userback.txt
    echo -e "$userback" > /root/userback.txt
		openssl enc -aes-128-cbc -salt -in ${ADM_tmp}/userback.txt -pass pass:ADMRufu -out ${ADM_tmp}/userback.enc > /dev/null 2>&1
		mv ${ADM_tmp}/userback.enc /root/user_$(printf '%(%d-%m-%y_%H:%M:%S)T').ADMRufu
		rm ${ADM_tmp}/userback.txt
		print_center -verd "Copia de seguridad creada."
		enter
		return
	}

  restor(){
    openssl enc -aes-128-cbc -d -in ${ADM_tmp}/userback.enc -pass pass:ADMRufu -out ${ADM_tmp}/userback.txt &>/dev/null 2>&1
    msg -nama " Eliminar todos los usuarios? [S/N]: " && read del_all
    [[ "$del_all" != @(S|s) ]] && msg -nama " Sobrescrivir usuarios exixtentes? [S/N]: " && read reset_user
    all_user=$(cat /etc/passwd|grep 'home'|grep 'false'|grep -v 'syslog')
    if [[ "$del_all" = @(S|s) ]]; then
      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
      title -ama "ELIMINADO TODOS LO USUARIOS...."
      for user_d in `echo "$all_user"|awk -F ':' '{print $1}'`; do
        userpid=$(ps -u $user_d |awk {'print $1'})
        kill "$userpid" 2>/dev/null
        userdel --force $user_d
      done
      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
    fi
    clear
    msg -bar
    print_center -ama "RESTAURANDO COPIA"
    msg -bar
    all_name=($(echo "$all_user"|awk -F ':' '{print $1}'))
    while read line; do
      user=$(echo $line|cut -d '|' -f1)
      pass=$(echo $line|cut -d '|' -f2)

      dias=$(( $(echo $line|cut -d '|' -f3) + 1 ))

      if [[ "$dias" -lt 1 ]]; then dias=0 ;fi

      dat=$(echo $line|cut -d '|' -f4)
      stat=$(echo $line|cut -d '|' -f5)

      if [[ $(echo "${all_name[@]}"|grep "$user") = "" ]]; then
        valid=$(date '+%C%y-%m-%d' -d " +$dias days")
        msg -nama " $user"
        if useradd -M -s /bin/false -e ${valid} -K PASS_MAX_DAYS=$dias -p $(openssl passwd -6 $pass) -c $dat $user ; then
          [[ "$stat" = "P" ]] && usermod -U $user || usermod -L $user
          msg -verd " $(fun_trans "Restaurado")"
        else
          msg -verm2 " $(fun_trans "NO, Usuario no Restaurado")"
        fi 
      else
        if [[ "$reset_user" = @(S|s) ]]; then
          userpid=$(ps -u $user |awk {'print $1'})
          kill "$userpid" 2>/dev/null
          userdel --force $user
          if useradd -M -s /bin/false -e ${valid} -K PASS_MAX_DAYS=$dias -p $(openssl passwd -6 $pass) -c $dat $user ; then
            [[ "$stat" = "P" ]] && usermod -U $user || usermod -L $user
            msg -verd " $(fun_trans "Restaurado")"
          else
            msg -verm2 " $(fun_trans "NO, Usuario no Restaurado")"
          fi
        else
            echo -e " $(msg -ama "$user") $(msg -verm2 "Ya Existe")"
        fi
      fi
    done <<< $(cat "${ADM_tmp}/userback.txt")

    rm ${ADM_tmp}/userback.enc
    rm ${ADM_tmp}/userback.txt
    enter

  }

	rsurs(){
		clear
		msg -bar
		print_center -ama "RESTAURAR COPIA DE SEGURIDAD"
		msg -bar
		n=0
		for i in ${backls[@]}; do
      let n++
			echo -e " $(msg -verd "[$n]") $(msg -verm2 ">") $(msg -azu "$i")"
		done
		back
    opcion=$(selection_fun $n)
		[[ "$opcion" = "0" ]] && return
		let opcion--
		cp /root/${backls[$opcion]} ${ADM_tmp}/userback.enc
    restor
    return
	}

	clbk(){
		rm -rf /root/*.ADMRufu
		clear
		msg -bar
		print_center -ama "REGITRO DE COPIAS ELIMINADO"
		enter
	}

  rest_online(){
    title -ama "URL DE COPIA EN LINEA"
    echo -e " $(msg -verm3 "╭╼╼╼╼╼╼╼╼╼╼╼╼╼╼╼╼[")$(msg -azu "INGRESA EL URL")$(msg -verm3 "]")"
    echo -ne " $(msg -verm3 "╰╼")\033[37;1m> " && read url
    [[ -z "$url" ]] && return
    wget -O ${ADM_tmp}/userback.enc "${url}" &>/dev/null; chmod +x ${ADM_tmp}/userback.enc
    restor
    return
  }

	backls=($(ls /root|grep '.ADMRufu'))
	var="${#backls[@]}"
	[[ ${var} = "0" ]] && bkusr && return
	title "RESPALDO DE USUARIOS"
	menu_func "CREAR NUEVO RESPALDO DE USUARIOS" "RESTAURAR RESPALDO DE USUARIOS" "RESPALDO EN LINEA $(msg -verm2 "beta")" "LIMPIAR REGISTRO DE COPIAS"
	back
	msg -ne " opcion: "
	read opcion
	case $opcion in
		1)bkusr;;
		2)rsurs;;
		3)rest_online;;
		4)clbk;;
		0)return;;
	esac
}

remove_script(){
	title "REMOVER SCRIPT ADMRufu"
	in_opcion "Remover script [S/N]"
	[[ "$opcion" != @(s|S|y|Y) ]] && return
	sed -i '/Rufu/d' /root/.bashrc
	sed -i '/Rufu/d' /etc/bash.bashrc
	rm -rf /usr/bin/menu
	rm -rf /usr/bin/adm
	rm -rf /usr/bin/ADMRufu
	rm -rf /etc/ADMRufu
	echo "SCRIPT REMOVIDO, REINICIANDO VPS"
	sleep 5
	reboot
}

update(){
	title "ESTA POR ACTUALIZAR ADMRufu"
	print_center -ama "Para actualizar ADMRufu, requiere de una key"
	msg -bar
	in_opcion "DESA CONTINUAR [S/N]"

	if [[ "$opcion" = @(s|S|y|Y) ]]; then
		rm -rf /root/install.sh*
		wget -O /root/install.sh https://raw.githubusercontent.com/rudi9999/ADMRufu/main/install.sh &>/dev/null
		chmod +x /root/install.sh*
		/root/install.sh --update
	fi
}

acount_mode(){
	[[ ! -e ${ADM_user}/userMODE ]] && echo "userSSH" > ${ADM_user}/userMODE
	mode=$(cat ${ADM_user}/userMODE)
	case $mode in
		userSSH)${ADM_inst}/userSSH;;
		userHWID)${ADM_inst}/userHWID;;
		userTOKEN)${ADM_inst}/userTOKEN;;
	esac
}

# EXECUCION DE MENU
export -f fun_trans
export -f fun_ip
export -f info_sys
export -f mine_port
export -f os_system
export -f fun_bar
export -f fun_eth
export -f mportas
export -f in_opcion
export -f droppids
export -f backup
export -f ULK_ALF
clear
#########VISUALIZACION DE MENU
cabesera
if [[ $(cat ${ADM_tmp}/style|grep -w "infsys"|awk '{print $2}') = "1" ]] ; then
  info_sys
  msg -bar
fi

if [[ $(cat ${ADM_tmp}/style|grep -w "port"|awk '{print $2}') = "1" ]] ; then
  mine_port
  msg -bar
fi

if [[ $(cat ${ADM_tmp}/style|grep -w "resel"|awk '{print $2}') = "1" ]] ; then
  echo -e "\033[1;34m $(cat ${ADM_tmp}/message.txt)\033[0m"
  msg -bar
fi

if [[ $(cat ${ADM_tmp}/style|grep -w "contador"|awk '{print $2}') = "1" ]] ; then
  contador
  msg -bar
fi

v=$(cat $ADMRufu/vercion)
up=$v && [[ -e "$ADMRufu/new_vercion" ]] && up=$(cat $ADMRufu/new_vercion)

menu_func "ADMINISTRAR CUENTAS (SSH/DROPBEAR)" \
"-bar3 ADMINISTRAR CUENTAS (V2ray)" \
"-bar3 \033[1;100mPREPARACION DEL SISTEMA\033[0m" \
"-vm DESINSTALAR PANEL"

r='5'; u='u'
if [[ "$(date '+%s' -d "$up")" -gt "$(date '+%s' -d "$v")" ]]; then
	msg -bar3
	r='6'; u='5'
	echo -e "$(msg -verd " [$u]") $(msg -verm2 ">") $(msg -azu "ACTUALIZAR:") $(msg -ama "$v") $(msg -verm2 ">>>") $(msg -verd "$up")"
fi
msg -bar && echo -ne "$(msg -verd " [0]") $(msg -verm2 ">") $(msg -bra "\033[1;41m SALIR DEL SCRIPT ")" && echo -e "$(msg -verd " [$r]") $(msg -verm2 ">") $(msg -bra "\033[1;44m REINICIAR VPS \033[0m")"
msg -bar
selection=$(selection_fun -nama $r)

case ${selection} in
	1)acount_mode;;
	2)${ADM_inst}/userV2ray.sh;;
	3)${ADMRufu}/menu_inst.sh;;
	4)remove_script;;
 "$r")reiniciar_vps;;
 "$u")update;;
	0)clear && cd $HOME && exit 0;;
esac
${ADMRufu}/menu

