#!/bin/bash
clear
ipsaya=$(wget -qO- ipinfo.io/ip)
data_server=$(curl -v --insecure --silent https://google.com/ 2>&1 | grep Date | sed -e 's/< Date: //')
date_list=$(date +"%Y-%m-%d" -d "$data_server")
data_ip="https://raw.githubusercontent.com/RozTun/permission/main/ip"
ISP=$(cat /etc/xray/isp)
CITY=$(cat /etc/xray/city)
PUB=$(cat /etc/slowdns/server.pub)
NS=$(cat /etc/xray/dns)
domain=$(cat /etc/xray/domain)
checking_sc() {
  useexp=$(wget -qO- $data_ip | grep $ipsaya | awk '{print $3}')
  if [[ $date_list < $useexp ]]; then
    echo -ne
  else
    echo -e "${OR}────────────────────────────────────────────${NC}"
    echo -e "\033[42m          HUNTERTUNNEL AUTOSCRIPT          ${NC}"
    echo -e "${OR}────────────────────────────────────────────${NC}"
    echo -e ""
    echo -e "            ${RED}PERMISSION DENIED !${NC}"
    echo -e "   \033[0;33mYour VPS${NC} $ipsaya \033[0;33mHas been Banned${NC}"
    echo -e "     \033[0;33mBuy access permissions for scripts${NC}"
    echo -e "             \033[0;33mContact Admin :${NC}"
    echo -e "      ${Green}WhatsApp${NC} wa.me/6285759375937"
    echo -e "         \033[0;36mTelegram${NC} t.me/RozTun"
    echo -e "${OR}────────────────────────────────────────────${NC}"
    exit
  fi
}
checking_sc
clear
    
# Variables
green="\e[38;5;82m"
red="\e[38;5;196m"
neutral="\e[0m"
OR="\e[38;5;130m"
orange="\e[38;5;130m"
blue="\e[38;5;39m"
yellow="\e[38;5;226m"
purple="\e[38;5;141m"
bold_white="\e[1;37m"
reset="\e[0m"

# Function to print rainbow text
        print_rainbow() {
            local text="$1"
            local length=${#text}
            local start_color=(0 5 0)
            local mid_color=(0 200 0)
            local end_color=(0 5 0)

            for ((i = 0; i < length; i++)); do
                local progress=$((i * 100 / (length - 1)))

                if [ $progress -lt 50 ]; then
                    local factor=$((progress * 2))
                    r=$(( (start_color[0] * (100 - factor) + mid_color[0] * factor) / 100 ))
                    g=$(( (start_color[1] * (100 - factor) + mid_color[1] * factor) / 100 ))
                    b=$(( (start_color[2] * (100 - factor) + mid_color[2] * factor) / 100 ))
                else
                    local factor=$(((progress - 50) * 2))
                    r=$(( (mid_color[0] * (100 - factor) + end_color[0] * factor) / 100 ))
                    g=$(( (mid_color[1] * (100 - factor) + end_color[1] * factor) / 100 ))
                    b=$(( (mid_color[2] * (100 - factor) + end_color[2] * factor) / 100 ))
                fi

                printf "\e[38;2;%d;%d;%dm%s" "$r" "$g" "$b" "${text:$i:1}"
            done
            echo -e "$reset" # Reset color at the end
        }

# Function to print rainbo text
print_rainbo() {
    local text="$1"
    local length=${#text}
    local start_color=(255 255 0) # yellow
    local mid_color=(0 255 0)     # green
    local end_color=(255 255 0)   # yellow

    for ((i = 0; i < length; i++)); do
        local progress=$((i * 100 / (length - 1)))

        if [ $progress -lt 50 ]; then
            local factor=$((progress * 2))
            r=$((start_color[0] * (100 - factor) / 100 + mid_color[0] * factor / 100))
            g=$((start_color[1] * (100 - factor) / 100 + mid_color[1] * factor / 100))
            b=$((start_color[2] * (100 - factor) / 100 + mid_color[2] * factor / 100))
        else
            local factor=$(((progress - 50) * 2))
            r=$((mid_color[0] * (100 - factor) / 100 + end_color[0] * factor / 100))
            g=$((mid_color[1] * (100 - factor) / 100 + end_color[1] * factor / 100))
            b=$((mid_color[2] * (100 - factor) / 100 + end_color[2] * factor / 100))
        fi

        printf "\e[38;2;%d;%d;%dm%s" "$r" "$g" "$b" "${text:$i:1}"
    done
    echo -e "$reset"
}

cleam() {
export TIME="10"
city=$(cat /etc/xray/city)
PUB=$(cat /etc/slowdns/server.pub)
NS=$(cat /etc/xray/dns)
IP=$(curl -sS ipv4.icanhazip.com)
ISP=$(cat /etc/xray/isp)
domain=$(cat /etc/xray/domain)

# Loading animation
echo ""
echo -ne "${yellow}Preparing Premium Account${reset}"
for i in {1..2}; do
    for j in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏; do
        echo -ne "\r${yellow}Preparing Premium Account $j${reset}"
        sleep 0.1
    done
done
echo -ne "\r${yellow}Premium Account Ready to be created!${reset}\n"
sleep 1
clear

# User data input
print_rainbo "┌─────────────────────────────────────────┐"
print_rainbo "│            ENTER USER DATA              │"
print_rainbo "└─────────────────────────────────────────┘"
while true; do
    read -p "   Name: " Login
    if [[ ${#Login} -lt 3 || ! "$Login" =~ ^[a-zA-Z0-9_-]+$ ]]; then
        printf "\033[1A\033[0J"
        echo -e "${red}   Username cannot be empty${reset}"
        continue
    fi
    if grep -q "^#ssh# $Login " /etc/ssh/.ssh.db; then
        random_number=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 5)
        Login="${random_number}${Login}"
        echo -e "${yellow}   Username already exists. New username used: $Login${reset}"
        break
    else
        break
    fi
done
echo ""
printf "\033[10A\033[0J"
print_rainbo "┌─────────────────────────────────────────┐"
print_rainbo "│   .::.  Script by HunterTunnel  .::.    │"
print_rainbo "│      Input ssh/openvpn account deps     │"
print_rainbo "│        Set IP Limit for Account         │"
print_rainbo "└─────────────────────────────────────────┘"
echo "   Username : $Login"
while true; do
    read -p "   Password: " pass
    if [[ -z "$pass" || ${#pass} -lt 1 ]]; then
        printf "\033[1A\033[0J"
        echo -e "\e[1;31m   Password must be at least 1 characters long.\e[0m"
        continue
    fi
    break
done

# Input IP Limit
while true; do
    read -p "   Limit (IP): " iplimit
    if [[ ! "$iplimit" =~ ^[0-9]+$ || $iplimit -le 0 ]]; then
        printf "\033[1A\033[0J"
        echo -e "\e[1;31m   IP limit must be a positive number.\e[0m"
        continue
    fi
    break
done

# Input Expiry
while true; do
    read -p "   Expired (days): " masaaktif
    if [[ ! "$masaaktif" =~ ^[0-9]+$ || $masaaktif -le 0 ]]; then
        printf "\033[1A\033[0J"
        echo -e "\e[1;31m   Expired days must be a positive number.\e[0m"
        continue
    fi
    break
done

# Handle IP Limit
if [[ $iplimit -gt 0 ]]; then
    mkdir -p /etc/biji/limit/ssh/ip/
    echo -e "$iplimit" > /etc/biji/limit/ssh/ip/$Login
fi

# Set Expiry Date
tgl=$(date -d "$masaaktif days" +"%d")
bln=$(date -d "$masaaktif days" +"%b")
thn=$(date -d "$masaaktif days" +"%Y")
expe="$tgl $bln, $thn"

# Add User and Set Password
useradd -e $(date -d "$masaaktif days" +"%Y-%m-%d") -s /bin/false -M $Login
echo -e "$pass\n$pass\n" | passwd $Login &> /dev/null

# Quota Handling (if needed)
if [ -z "${Quota}" ]; then
    Quota="0"
fi
c=$(echo "${Quota}" | sed 's/[^0-9]*//g')
d=$((c * 1024 * 1024 * 1024))
if [[ $c -ne 0 ]]; then
    echo "${d}" > /etc/ssh/${Login}
fi

# Save to Database
if [[ -e /etc/ssh/.ssh.db ]]; then
    sed -i "/\b${Login}\b/d" /etc/ssh/.ssh.db
fi
echo "#ssh# ${Login} ${pass} ${Quota} ${iplimit} ${expe}" >> /etc/ssh/.ssh.db

cat > /var/www/html/ssh-$Login.txt <<-END
---------------------
SSH OVPN Account Details
---------------------
Username         : $Login
Password         : $pass
---------------------
IP               : $IP
Host             : $domain
Slowdns Host     : ${NS}
Public Key       : ${PUB}
Location         : $CITY
OpenSSH Port     : 443, 80, 22
UdpSSH Port      : 1-65535
Dropbear Port    : 443, 109
Dropbear WS Port : 443, 109
SSH WS Port      : 80
SSH SSL WS Port  : 443
SSL/TLS Port     : 443
OVPN WS SSL Port : 443
OVPN SSL Port    : 443
OVPN TCP Port    : 443, 1194
OVPN UDP Port    : 2200
BadVPN UDP       : 7100, 7300, 7300
---------------------
WSS Payload: GET wss://BUG.COM/ HTTP/1.1[crlf]Host: $domain[crlf]Upgrade: websocket[crlf][crlf] 
---------------------
OpenVPN Link     : http://$domain:85
---------------------
Expiration       : $expe
END

# Output Account Details
clear
print_rainbo "───────────────────────────"
print_rainbo "     SSH OVPN Account      "
print_rainbo "───────────────────────────"
echo -e "Username         : $Login"
echo -e "Password         : $pass"
echo -e "IP Limit         : $iplimit Device"
print_rainbo "───────────────────────────"
echo -e "Host             : $domain"
echo -e "Slowdns Host     : ${NS}"
echo -e "Provaider        : $ISP"
echo -e "Location         : $city"
echo -e "OpenSSH Port     : 443, 80, 22"
echo -e "UdpSSH Port      : 1-65535"
echo -e "DNS Port         : 443, 53, 22"
echo -e "Dropbear Port    : 443, 109"
echo -e "SSH WS Port      : 80"
echo -e "SSH SSL WS Port  : 443"
echo -e "SSL/TLS Port     : 443"
echo -e "OVPN SSL Port    : 443"
echo -e "OVPN TCP Port    : 1194"
echo -e "OVPN UDP Port    : 2200"
echo -e "BadVPN UDP       : 7100, 7300, 7300"
echo -e "SlowDns Public Key: ${PUB}"
print_rainbo "───────────────────────────"
echo -e "WSS Payload      : GET wss://BUG.COM/ HTTP/1.1[crlf]Host: $domain[crlf]Upgrade: websocket[crlf][crlf]"
print_rainbo "───────────────────────────"
echo -e "OpenVPN Link     : https://$domain:81/allovpn.zip"
print_rainbo "───────────────────────────"
echo -e "Save Account Link: https://$domain:81/ssh-$Login.txt"
print_rainbo "───────────────────────────"
echo -e "Day Exp          : $masaaktif Day"
echo -e "Expiration       : $expe"
print_rainbo "───────────────────────────"
echo -e ""

read -n 1 -s -r -p "Enter Back To Menu"
aphace
}

trialssh() {
# Getting
ISP=$(curl -s ipinfo.io/org | cut -d " " -f 2-10 )
CITY=$(curl -s ipinfo.io/city )
domain=$(cat /etc/xray/domain)
nama=$(cat /etc/xray/username)
clear
IP=$(curl -sS ipv4.icanhazip.com)
Login=TrialHT-`</dev/urandom tr -dc X-Z0-9 | head -c4`
hari="1"
Pass=1
iplimit=99
#limitip
if [[ $iplimit -gt 0 ]]; then
mkdir -p /etc/biji/limit/ssh/ip/
echo -e "$iplimit" > /etc/biji/limit/ssh/ip/$Login
else
echo > /dev/null
fi
clear
ISP=$(cat /etc/xray/isp)
CITY=$(cat /etc/xray/city)
PUB=$(cat /etc/slowdns/server.pub)
NS=$(cat /etc/xray/dns)
clear
tgl=$(date -d "$masaaktif days" +"%d")
bln=$(date -d "$masaaktif days" +"%b")
thn=$(date -d "$masaaktif days" +"%Y")
expe="$tgl $bln, $thn"
tgl2=$(date +"%d")
bln2=$(date +"%b")
thn2=$(date +"%Y")
tnggl="$tgl2 $bln2, $thn2"
useradd -e `date -d "$masaaktif days" +"%Y-%m-%d"` -s /bin/false -M $Login
exp="$(chage -l $Login | grep "Account expires" | awk -F": " '{print $2}')"
hariini=`date -d "0 days" +"%Y-%m-%d"`
expi=`date -d "$masaaktif days" +"%Y-%m-%d"`
echo -e "$Pass\n$Pass\n"|passwd $Login &> /dev/null

# Loading animation
echo ""
echo -ne "${yellow}Preparing Premium Account${reset}"
for i in {1..2}; do
    for j in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏; do
        echo -ne "\r${yellow}Preparing Premium Account $j${reset}"
        sleep 0.1
    done
done
echo -ne "\r${yellow}Premium Account Ready to be created!${reset}\n"
sleep 1
clear

# User data input
print_rainbo "┌─────────────────────────────────────────┐"
print_rainbo "│   .::.  Script by HunterTunnel  .::.    │"
print_rainbo "│     Input SSH trial account data        │"
print_rainbo "│            Enter User Data              │"
print_rainbo "└─────────────────────────────────────────┘"
echo 
echo -e "${yellow}exemple ( 1m for minutes, 1d for days) ${neutral} "
echo 
read -p "Input Time Duration : " duration
unit=${duration: -1}  
value=${duration%?}  

# Validasi input
if [[ ! $value =~ ^[0-9]+$ ]]; then
    echo "Invalid input! Format harus angka diikuti huruf 'm' atau 'd'."
    exit 1
fi

# Menentukan durasi dalam menit dan detail
if [[ $unit == "m" || $unit == "M" ]]; then
    pup=$value
    detail="$value minutes"
elif [[ $unit == "d" || $unit == "D" ]]; then
    pup=$((value * 1440))  # Mengkonversi hari ke menit
    detail="$value Days"
else
    echo "Invalid format! Gunakan 'm' untuk menit atau 'd' untuk hari."
    exit 1
fi

echo "Akun akan berakhir dalam $detail."

# Menghapus akun setelah durasi habis
echo userdel ${Login} | at now + $pup minutes &> /dev/null

echo "Restarting SSHD..."
systemctl restart sshd

# Membuat file informasi akun
mkdir -p /etc/ssh

if [[ ${c} != "0" ]]; then
    echo "${d}" >/etc/ssh/${Login}
fi

cat > /var/www/html/ssh-$Login.txt <<-END
======================
Format SSH OVPN Account
======================
Username         : $Login
Password         : $Pass
Berakhir Dalam   : $detail
======================
IP               : $IP
Host             : $domain
Port OpenSSH     : 443, 80, 22
Port Dropbear    : 443, 109
Port SSH WS      : 80, 8080
Port SSH SSL WS  : 443
Port OVPN SSL    : 443
======================
OVPN Download    : https://$domain:81/
======================
END

clear
print_rainbo "───────────────────────────"
print_rainbo "     SSH OVPN Account      "
print_rainbo "───────────────────────────"
echo -e "Username         : $Login"
echo -e "Password         : $Pass"
echo -e "IP Limit         : $iplimit"
print_rainbo "───────────────────────────"
echo -e "Host             : $domain"
echo -e "Slowdns Host     : ${NS}"
echo -e "Provaider        : $ISP"
echo -e "Location         : $CITY"
echo -e "OpenSSH Port     : 443, 80, 22"
echo -e "UdpSSH Port      : 1-65535"
echo -e "DNS Port         : 443, 53, 22"
echo -e "Dropbear Port    : 443, 109"
echo -e "SSH WS Port      : 80"
echo -e "SSH SSL WS Port  : 443"
echo -e "SSL/TLS Port     : 443"
echo -e "OVPN SSL Port    : 443"
echo -e "OVPN TCP Port    : 1194"
echo -e "OVPN UDP Port    : 2200"
echo -e "BadVPN UDP       : 7100, 7300, 7300"
echo -e "SlowDns Public Key: ${PUB}"
print_rainbo "───────────────────────────"
echo -e "WSS Payload      : GET wss://BUG.COM/ HTTP/1.1[crlf]Host: $domain[crlf]Upgrade: websocket[crlf][crlf]"
print_rainbo "───────────────────────────"
echo -e "OpenVPN Link     : https://$domain:81/allovpn.zip"
print_rainbo "───────────────────────────"
echo -e "Save Account Link: https://$domain:81/ssh-$Login.txt"
print_rainbo "───────────────────────────"
echo -e "Expiration       : $detail"
print_rainbo "───────────────────────────"
echo -e ""

read -n 1 -s -r -p "Enter Back To Menu"
aphace
}

detailssh() {
clear
echo -e "${orange}┌──────────────────────────────────────┐${neutral}"
echo -e "${orange}│       ${green}SSH OVPN ACCOUNT DETAILS${neutral}       ${orange}│${neutral}"
echo -e "${orange}└──────────────────────────────────────┘${neutral}"
# Header untuk output
echo -e "${orange}┌──────────────────────────────────────┐${neutral}"
printf  "${green} %-15s %-10s %-15s${neutral}\n" "Username" "Days Left" "Status"
echo -e "${orange} --------------------------------------${neutral}"
while read expired
do
AKUN="$(echo $expired | cut -d: -f1)"
    ID="$(echo $expired | grep -v nobody | cut -d: -f3)"
    exp="$(chage -l $AKUN | grep "Account expires" | awk -F": " '{print $2}')"
    status="$(passwd -S $AKUN | awk '{print $2}' )"
    
    if [[ $ID -ge 1000 ]]; then
        if [[ "$exp" != "never" ]]; then
            exp_date=$(date -d "$exp" +%s)
            current_date=$(date +%s)
            days_left=$(( (exp_date - current_date) / 86400 ))
        else
            days_left="never"
        fi
        
        if [[ "$status" = "L" ]]; then
            printf  " %-15s %-10s %-15s\n" "$AKUN" "$days_left Days" "LOCKED${NORMAL}"
        else
            printf  " %-15s %-10s %-15s\n" "$AKUN" "$days_left Days" "UNLOCKED${NORMAL}"
        fi
fi
done < /etc/passwd
echo -e "${orange}└──────────────────────────────────────┘${neutral}"
print_rainbow "─────────────────────────────────────────"
read -rp " Type the Username : " user
if [ -z $user ]; then
echo -e "User Tidak Ditemukan!!!"
read -n 1 -s -r -p " Enter Back To Menu"
aphace
else
clear
cat /var/www/html/ssh-$user.txt
read -n 1 -s -r -p " Enter Back To Menu"
aphace
fi
}

change_ip_ssh() {
  clear
  echo -e "${orange}──────────────────────────────────────────── ${neutral}"
  echo -e "${green}      .::::. CHANGE SSH IP .::::.          ${neutral}"
  echo -e "${orange}──────────────────────────────────────────── ${neutral}"
  echo -e " List change ssh account : "
  echo -e "┌────┬──────────────┬────────────┬──────┬──────────┐"
  echo -e "│ NO │ USERNAME     │ EXP DATE   │ DAYS │ STATUS   │"
  echo -e "├────┼──────────────┼────────────┼──────┼──────────┤"

  # Mengambil username dan nomor urutnya
  counter=1
  declare -A username_map
  while read expired
  do
    AKUN="$(echo $expired | cut -d: -f1)"
    ID="$(echo $expired | grep -v nobody | cut -d: -f3)"
    exp="$(chage -l $AKUN | grep "Account expires" | awk -F": " '{print $2}')"
    status="$(passwd -S $AKUN | awk '{print $2}' )"
    
    if [[ $ID -ge 1000 ]]; then
      # Mengubah bulan ke format nomor
      exp_month=$(date -d "$exp" +%m)
      exp_day=$(date -d "$exp" +%d)
      exp_year=$(date -d "$exp" +%Y)
      exp_formatted="$exp_day/$exp_month/$exp_year"

      d1="$(date -d "$exp" +%s)"
      d2="$(date -d "$today" +%s)"
      daylift="$(((d1 - d2) / 86400))"
      
      if [[ "$status" = "L" ]]; then
        # Memastikan kolom lebih rata
        printf "│ %-2s │ %-12s │ %-10s │ %-4s │ %-8s │\n" "$counter" "$AKUN" "$exp_formatted" "${daylift}d" "LOCKED"
      else
        printf "│ %-2s │ %-12s │ %-10s │ %-4s │ %-8s │\n" "$counter" "$AKUN" "$exp_formatted" "${daylift}d" "UNLOCKED"
      fi
      # Menyimpan username dengan nomor urut
      username_map[$counter]=$AKUN
      ((counter++))
    fi
  done < /etc/passwd

  echo -e "└────┴──────────────┴────────────┴──────┴──────────┘"  
  echo " "

  # Input nomor atau username, dengan pengecekan agar tidak kosong atau 0
  while true; do
    read -p "Input number or username to change IP: " input

    if [[ -z "$input" || "$input" == "0" ]]; then
      echo -e "${red}Input tidak boleh kosong atau 0! Silakan coba lagi.${neutral}"
      continue
    fi

    # Cek apakah input adalah nomor dan ambil username
    if [[ $input =~ ^[0-9]+$ ]]; then
      user=${username_map[$input]}
    else
      user=$input
    fi
    
    break
  done

  limit_file="/etc/biji/limit/ssh/ip/$user"

  # Validasi apakah file batasan IP sudah ada
  if [ -e "$limit_file" ]; then
    current_iplimit=$(cat "$limit_file")
    print_rainbow "────────────────────────────────────────────  "
    echo -e "${Cyan} Before ${neutral} "
    echo -e ""
    echo -e "${yellow} Username   : $user ${neutral} "
    echo -e "${yellow} Ip Limit   : $current_iplimit ${neutral} "
    echo -e ""
    print_rainbow "────────────────────────────────────────────  "
    while true; do
      read -p "Input New Ip   : " new_iplimit

      # Validasi jika masukan kosong atau 0
      if [ -z "$new_iplimit" ]; then
        echo -e "${red} Invalid !! ${neutral}"
      elif [ "$new_iplimit" == "0" ]; then
        echo -e "${red}No unlimited IP! Silakan masukkan IP yang valid.${neutral}"
      else
        # Update IP baru ke file
        echo "$new_iplimit" > "$limit_file"
        print_rainbow "────────────────────────────────────────────  "
        echo -e "${green} Successfully ${neutral} "
        echo -e ""
        echo -e "${green} After ${neutral} "
        echo -e ""
        echo -e "${yellow} New Ip   : $new_iplimit ${neutral} "
        echo -e "${yellow} Username : $user ${neutral} "
        echo -e ""
        print_rainbow "────────────────────────────────────────────  "
        break
      fi
    done
  else
    print_rainbow "────────────────────────────────────────────  "
    echo -e "${red} Sorry ${neutral} "
    echo ""
    echo -e "${yellow} Username   : $user ${neutral} "
    echo -e "${yellow} IP LIMIT   : invalid !! ${neutral} "
    echo ""
   print_rainbow "────────────────────────────────────────────  "
    echo ""
    read -n 1 -s -r -p "Press any key to back"
    aphace
  fi
}

renewssh() {
  clear
  echo -e "${orange}─────────────────────────────────────────${neutral}"
  echo -e "    ${green}.::::. RENEW SSH ACCOUNT .::::.${neutral}"
  echo -e "${orange}─────────────────────────────────────────${neutral}"
  echo -e " List renew ssh account : "
  echo -e "┌────┬──────────────┬────────────┬─────────────┐"
  echo -e "│ NO │ USERNAME     │ EXP DATE   │ STATUS      │"
  echo -e "├────┼──────────────┼────────────┼─────────────┤"

  counter=1
  while read expired
  do
    AKUN="$(echo $expired | cut -d: -f1)"
    ID="$(echo $expired | grep -v nobody | cut -d: -f3)"
    exp="$(chage -l $AKUN | grep "Account expires" | awk -F": " '{print $2}')"
    status="$(passwd -S $AKUN | awk '{print $2}' )"
    if [[ $ID -ge 1000 ]]; then
      # Mengubah bulan ke format nomor
      exp_month=$(date -d "$exp" +%m)
      exp_day=$(date -d "$exp" +%d)
      exp_year=$(date -d "$exp" +%Y)
      exp_formatted="$exp_day/$exp_month/$exp_year"

      if [[ "$status" = "L" ]]; then
        # Format output dengan lebar kolom yang konsisten
        printf "│ %-2s │ %-12s │ %-10s │ %-11s │\n" "$counter" "$AKUN" "$exp_formatted" "LOCKED"
      else
        printf "│ %-2s │ %-12s │ %-10s │ %-11s │\n" "$counter" "$AKUN" "$exp_formatted" "UNLOCKED"
      fi
      ((counter++))
    fi
  done < /etc/passwd

  echo -e "└────┴──────────────┴────────────┴─────────────┘"

  echo -e ""
  while true; do
    read -p "Username or Number: " input

    # Validasi input tidak boleh 0
    if [[ "$input" == "0" ]]; then
      echo -e "${red}Invalid input! You cannot select '0'. Please try again.${neutral}"
      continue
    fi

    # Cek apakah input adalah angka dan lebih besar dari 0
    if [[ "$input" =~ ^[0-9]+$ && "$input" -gt 0 ]]; then
      username=$(awk -F: '$3 >= 1000 && $1 != "nobody" {print $1}' /etc/passwd | sed -n "${input}p")
      break
    elif [[ "$input" =~ ^[a-zA-Z0-9_]+$ ]]; then
      username="$input"
      break
    else
      echo -e "${orange}─────────────────────────────────────────${neutral}"
      echo -e "     Invalid Username or Number             "
      echo -e "${orange}─────────────────────────────────────────${neutral}"
      continue
    fi
  done

  egrep "^$username" /etc/passwd >/dev/null
  if [ $? -eq 0 ]; then
    while true; do
      read -p "Day Extend (must be > 0): " Days

      # Validasi jika input Days adalah 0 atau kosong
      if [[ -z "$Days" || "$Days" -le 0 ]]; then
        echo -e "${red}Invalid input! The day extension must be greater than 0.${neutral}"
        continue
      fi

      Today=$(date +%s)
      Days_Detailed=$(( Days * 86400 ))
      Expire_On=$(( Today + Days_Detailed ))
      Expiration=$(date -u --date="1970-01-01 $Expire_On sec GMT" +%Y/%m/%d)
      Expiration_Display=$(date -u --date="1970-01-01 $Expire_On sec GMT" '+%d %b %Y')
      tgl=$(date -d "$Days days" +"%d")
      bln=$(date -d "$Days days" +"%m")
      thn=$(date -d "$Days days" +"%Y")
      expe="$tgl $bln, $thn"
      expi=$(cat /etc/ssh/.ssh.db | grep -wE "$username" | cut -d " " -f6-8)
      sed -i "s/$expi/$expe/" /etc/ssh/.ssh.db
      passwd -u $username
      usermod -e $Expiration $username
      egrep "^$username" /etc/passwd >/dev/null
      echo -e "$Pass\n$Pass\n"|passwd $username &> /dev/null
      clear
      echo -e "${orange}─────────────────────────────────────────${neutral}"
      echo -e "    Successfully Renewed SSH Account           "
      echo -e "${orange}─────────────────────────────────────────${neutral}"
      echo -e ""
      echo -e " Username   : $username"
      echo -e " Days Added : $Days Days"
      echo -e " Expires on : $Expiration_Display"
      echo -e ""
      print_rainbow "────────────────────────────────────────────  "
      echo -e ""
      read -n 1 -s -r -p "Press any key to back"
      aphace
      break
    done
  else
    clear
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "        Invalid Renew SSH Account             "
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e ""
    echo -e "   Username or Number Not Found      "
    echo -e ""
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e ""
    read -n 1 -s -r -p "Press any key to back"
    aphace
  fi
}

dellssh() {
clear
echo -e "${orange}───────────────────────────────────────── ${neutral}"
echo -e "${green}    .::::. DELETE SSH ACCOUNT .::::.     ${neutral}"
echo -e "${orange}───────────────────────────────────────── ${neutral}"
echo -e " List delete ssh account : "
echo -e "┌───┬──────────────┬────────────┬─────────────┐"
echo -e "│ NO│ USERNAME     │ EXP DATE   │ STATUS      │"
echo -e "├───┼──────────────┼────────────┼─────────────┤"

counter=1
declare -A users_list  # Menyimpan username berdasarkan nomor
while read expired
do
  AKUN="$(echo $expired | cut -d: -f1)"
  ID="$(echo $expired | grep -v nobody | cut -d: -f3)"
  exp="$(chage -l $AKUN | grep "Account expires" | awk -F": " '{print $2}')"
  status="$(passwd -S $AKUN | awk '{print $2}' )"
  if [[ $ID -ge 1000 ]]; then
    # Mengubah bulan ke format nomor
    exp_month=$(date -d "$exp" +%m)
    exp_day=$(date -d "$exp" +%d)
    exp_year=$(date -d "$exp" +%Y)
    exp_formatted="$exp_day/$exp_month/$exp_year"

    if [[ "$status" = "L" ]]; then
      printf "│ %-1s │ %-12s │ %-10s │ %-11s │\n" "$counter" "$AKUN" "$exp_formatted" "LOCKED"
    else
      printf "│ %-1s │ %-12s │ %-10s │ %-11s │\n" "$counter" "$AKUN" "$exp_formatted" "UNLOCKED"
    fi

    # Simpan username sesuai nomor
    users_list[$counter]=$AKUN
    ((counter++))
  fi
done < /etc/passwd

echo -e "└───┴──────────────┴────────────┴─────────────┘"  
echo " "

# Input username atau nomor
read -p "Input Username or Number: " input

# Jika input berupa angka, cari username yang sesuai
if [[ "$input" =~ ^[0-9]+$ ]]; then
  username="${users_list[$input]}"
else
  username=$input
fi

# Proses delete jika username ditemukan
if [[ -n "$username" && $(getent passwd "$username") ]]; then
  userdel -r "$username"  # Hapus akun beserta home directory-nya
  clear
  print_rainbow "────────────────────────────────────────────  "
  echo -e "${green}  Successfully Deleted SSH Account ${neutral}"
  echo -e "${green}  Username  : $username ${neutral}"
  print_rainbow "────────────────────────────────────────────  "
  read -n 1 -s -r -p "Press any key to back"
  aphace
else
  # Jika username tidak valid
  clear
  echo -e "${orange}───────────────────────────────────────── ${neutral}"
  echo -e "${red} Failure: User unknown. ${neutral}"
  echo -e "${orange}───────────────────────────────────────── ${neutral}"
  read -n 1 -s -r -p "Press any key to back"
  aphace
fi
}

lock_ssh() {
  clear
  echo -e "${orange}─────────────────────────────────────────${neutral}"
  echo -e "   ${green}.::::. LOCK SSH ACCOUNT .::::.${neutral}"
  echo -e "${orange}─────────────────────────────────────────${neutral}"
  echo -e " List lock ssh account : "
  echo -e "┌───┬──────────────┬────────────┬─────────────┐"
  echo -e "│ NO│ USERNAME     │ EXP DATE   │ STATUS      │"
  echo -e "├───┼──────────────┼────────────┼─────────────┤"

  counter=1
  declare -A users_list  # Array untuk menyimpan username berdasarkan nomor
  while read expired
  do
    AKUN="$(echo $expired | cut -d: -f1)"
    ID="$(echo $expired | grep -v nobody | cut -d: -f3)"
    exp="$(chage -l $AKUN | grep "Account expires" | awk -F": " '{print $2}')"
    status="$(passwd -S $AKUN | awk '{print $2}' )"
    if [[ $ID -ge 1000 ]]; then
      # Mengubah bulan ke format nomor
      exp_month=$(date -d "$exp" +%m)
      exp_day=$(date -d "$exp" +%d)
      exp_year=$(date -d "$exp" +%Y)
      exp_formatted="$exp_day/$exp_month/$exp_year"

      if [[ "$status" = "L" ]]; then
        # Format output dengan lebar kolom yang konsisten
        printf "│ %-2s│ %-12s │ %-10s │ %-11s │\n" "$counter" "$AKUN" "$exp_formatted" "LOCKED"
      else
        printf "│ %-2s│ %-12s │ %-10s │ %-11s │\n" "$counter" "$AKUN" "$exp_formatted" "UNLOCKED"
      fi

      # Simpan username sesuai nomor urut
      users_list[$counter]=$AKUN
      ((counter++))
    fi
  done < /etc/passwd

  echo -e "└───┴──────────────┴────────────┴─────────────┘"  
  echo " "

  # Input username atau nomor
  read -p "Input number or Username for lock: " input

  # Jika input berupa angka, cari username yang sesuai
  if [[ "$input" =~ ^[0-9]+$ ]]; then
    username="${users_list[$input]}"
  else
    username=$input
  fi

  # Proses lock akun jika ditemukan
  if [[ -n "$username" && $(getent passwd "$username") ]]; then
    passwd -l "$username"
    clear
    echo " "
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "${green} Successfully locked ${neutral}"
    echo -e ""
    echo -e "${yellow} Username  : $username ${neutral}"
    echo -e "${yellow} Status    : LOCKED!! ${neutral}"
    echo -e ""
    print_rainbow "────────────────────────────────────────────  "
  else
    # Jika username tidak ditemukan
    echo "Username not found on your server."
  fi

  read -n 1 -s -r -p "Press any key to back"
  aphace
}

unlock_ssh() {
  clear
  echo -e "${orange}─────────────────────────────────────────${neutral}"
  echo -e "    ${green}.::::. UNLOCK SSH ACCOUNT .::::.${neutral}"
  echo -e "${orange}─────────────────────────────────────────${neutral}"
  echo -e " List unlock ssh account : "
  echo -e "┌───┬──────────────┬────────────┬─────────────┐"
  echo -e "│ NO│ USERNAME     │ EXP DATE   │ STATUS      │"
  echo -e "├───┼──────────────┼────────────┼─────────────┤"

  counter=1
  declare -A users_list  # Array untuk menyimpan username berdasarkan nomor
  while read expired
  do
    AKUN="$(echo $expired | cut -d: -f1)"
    ID="$(echo $expired | grep -v nobody | cut -d: -f3)"
    exp="$(chage -l $AKUN | grep "Account expires" | awk -F": " '{print $2}')"
    status="$(passwd -S $AKUN | awk '{print $2}' )"
    if [[ $ID -ge 1000 ]]; then
      # Mengubah bulan ke format nomor
      exp_month=$(date -d "$exp" +%m)
      exp_day=$(date -d "$exp" +%d)
      exp_year=$(date -d "$exp" +%Y)
      exp_formatted="$exp_day/$exp_month/$exp_year"

      if [[ "$status" = "L" ]]; then
        # Format output dengan lebar kolom yang konsisten
        printf "│ %-2s│ %-12s │ %-10s │ %-11s │\n" "$counter" "$AKUN" "$exp_formatted" "LOCKED"
      else
        printf "│ %-2s│ %-12s │ %-10s │ %-11s │\n" "$counter" "$AKUN" "$exp_formatted" "UNLOCKED"
      fi

      # Simpan username sesuai nomor urut
      users_list[$counter]=$AKUN
      ((counter++))
    fi
  done < /etc/passwd

  echo -e "└───┴──────────────┴────────────┴─────────────┘"  
  echo " "

  # Input username atau nomor
  read -p "Input number or Username to Unlock: " input

  # Jika input berupa angka, cari username yang sesuai
  if [[ "$input" =~ ^[0-9]+$ ]]; then
    username="${users_list[$input]}"  # Mengambil username berdasarkan nomor urut
  else
    username=$input  # Menggunakan input langsung sebagai username
  fi

  # Proses membuka kunci akun
  if [[ -n "$username" && $(getent passwd "$username") ]]; then
    passwd -u "$username" >/dev/null 2>&1
    clear
    echo " "
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo ""
    echo -e "${green} Successfully Unlocked ${neutral}"
    echo ""
    echo -e "${green} Username  : $username ${neutral}"
    echo -e "${green} Status    : UNLOCKED ${neutral}"
    echo ""
    print_rainbow "────────────────────────────────────────────  "
    read -n 1 -s -r -p "Press any key to back"
    aphace
  else
    # Jika input salah atau tidak ditemukan
    clear
    echo " "
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "${red} Error: Invalid Username or Number ${neutral}"
    echo ""
    echo -e "${yellow} Input     : $input ${neutral}"
    echo -e "${red} Status    : NOT FOUND!! ${neutral}"
    echo ""
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    read -n 1 -s -r -p "Press any key to back"
    aphace
  fi
}

checkssh() {
    # Membersihkan layar
    clear

    # Header
    echo -e "${orange}──────────────────────────────────────────── ${neutral}"
    echo -e "${green}      .::::. CHECK LOGIN SSH .::::.          ${neutral}"
    echo -e "${orange}──────────────────────────────────────────── ${neutral}"
    echo -e " List user login ssh account : "
    # Inisialisasi file sistem
    touch /root/.system
    dir="/etc/biji/limit/ssh/ip"

    # Ambil semua user dengan UID >= 1000 kecuali "nobody"
    data1=( $(awk -F: '$3 >= 1000 && $1 != "nobody" {print $1}' /etc/passwd) )
    
    # Pastikan file IP limit ada untuk setiap user
    for user in "${data1[@]}"; do
        iplimit1="$dir/$user"
        # Jika direktori tidak ada, buat
        [[ ! -d $dir ]] && mkdir -p $dir
        # Jika file tidak ada atau kosong, buat dengan default "2"
        [[ ! -f $iplimit1 || ! -s $iplimit1 ]] && echo "2" > $iplimit1
    done

    # Ambil informasi login pengguna
    mulog=$(cekssh)
    data=( $(awk -F: '$3 >= 1000 && $1 != "nobody" {print $1}' /etc/passwd) )

    # Tabel header
    printf "┌───────────────┬─────────────┬─────────────┐\n"
    printf "│ %-13s │ %-11s │ %-11s │\n" "USERNAME" "IP LIMIT" "IP LOGIN"
    printf "├───────────────┼─────────────┼─────────────┤\n"

    # Iterasi setiap user dan tampilkan informasi login
    for user in "${data[@]}"; do
        cekcek=$(echo -e "$mulog" | grep -wE "$user" | wc -l)
        if [[ $cekcek -gt 0 ]]; then
            iplimit=$(cat /etc/biji/limit/ssh/ip/$user)
            printf "│ %-13s │ %-11s │ %-11s │\n" "$user" "${iplimit} IP" "${cekcek} IP"
            echo "slot" >> /root/.system
        fi
    done

    # Tabel footer
    printf "└───────────────┴─────────────┴─────────────┘\n"

    # Total user online
    aktif=$(cat /root/.system | wc -l)
    print_rainbow "────────────────────────────────────────────  "
    echo -e "               $aktif User Online"
    print_rainbow "────────────────────────────────────────────  "
 
    # Bersihkan file sementara
    sed -i "d" /root/.system   

    # Tunggu input sebelum kembali
    read -n 1 -s -r -p "Press any key to back"
    aphace
}

member_ssh() {
clear
echo -e "${orange}──────────────────────────────────────────── ${neutral}"
echo -e "${green}      .::::. MEMBER SSH ACCOUNT .::::.     ${neutral}"
echo -e "${orange}──────────────────────────────────────────── ${neutral}"
echo -e " List member ssh account : "
echo -e "┌────┬──────────────┬────────────┬──────┬──────────┐"
echo -e "│ NO │ USERNAME     │ EXP DATE   │ DAYS │ STATUS   │"
echo -e "├────┼──────────────┼────────────┼──────┼──────────┤"

counter=1
while read expired
do
  AKUN="$(echo $expired | cut -d: -f1)"
  ID="$(echo $expired | grep -v nobody | cut -d: -f3)"
  exp="$(chage -l $AKUN | grep "Account expires" | awk -F": " '{print $2}')"
  status="$(passwd -S $AKUN | awk '{print $2}' )"
  if [[ $ID -ge 1000 ]]; then
    # Mengubah bulan ke format nomor
    exp_month=$(date -d "$exp" +%m)
    exp_day=$(date -d "$exp" +%d)
    exp_year=$(date -d "$exp" +%Y)
    exp_formatted="$exp_day/$exp_month/$exp_year"

    d1="$(date -d "$exp" +%s)"
    d2="$(date -d "$today" +%s)"
    daylift="$(((d1 - d2) / 86400))"
    
    if [[ "$status" = "L" ]]; then
      # Memastikan kolom lebih rata
      printf "│ %-2s │ %-12s │ %-10s │ %-4s │ %-8s │\n" "$counter" "$AKUN" "$exp_formatted" "${daylift}d" "LOCKED"
    else
      printf "│ %-2s │ %-12s │ %-10s │ %-4s │ %-8s │\n" "$counter" "$AKUN" "$exp_formatted" "${daylift}d" "UNLOCKED"
    fi
    ((counter++))
  fi
done < /etc/passwd

echo -e "└────┴──────────────┴────────────┴──────┴──────────┘"  
echo " "

JUMLAH="$(awk -F: '$3 >= 1000 && $1 != "nobody" {print $1}' /etc/passwd | wc -l)"
print_rainbow "────────────────────────────────────────────  "
echo -e "${green}          Account Number: $JUMLAH user               ${Suffix}"
print_rainbow "────────────────────────────────────────────  "
echo -e ""
read -n 1 -s -r -p "Press any key to back"
aphace
}

        function autokill_ssh() {
            local sts=$(grep -qE "^SHELL" /etc/cron.d/autokill && echo -e "\033[32m[ON]\033[0m" || echo -e "\033[31m[OFF]\033[0m")
            clear
            echo -e "${orange}┌──────────────────────────────────────┐${neutral}"
            echo -e "${orange}│${green}         SSH OVPN AUTO KILL           ${orange}│${neutral}"
            echo -e "${orange}└──────────────────────────────────────┘${neutral}"
            echo -e "${orange}┌──────────────────────────────────────┐${neutral}"
            echo -e "${orange}│${neutral} Autokill Status: $sts"
            echo -e "${orange}│${neutral} 1) AutoKill After 5 Minutes"
            echo -e "${orange}│${neutral} 2) AutoKill After 10 Minutes"
            echo -e "${orange}│${neutral} 3) AutoKill After 15 Minutes"
            echo -e "${orange}│${neutral} 4) Disable AutoKill/MultiLogin"
            echo -e "${orange}│${neutral} x) Exit"
            echo -e "${orange}└──────────────────────────────────────┘${neutral}"

            read -p "Choose an option [1-4 or x]: " pilihan
            case $pilihan in
            1)
                echo -e "SHELL=/bin/sh\nPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\n*/5 * * * * root /usr/bin/malhware" >/etc/cron.d/autokill
                clear
                print_rainbow "────────────────────────────────────────"
                echo -e "${orange}│${neutral}"
                echo -e "${orange}│${neutral}      AutoKill: Every 5 Minutes"
                echo -e "${orange}│${neutral}"
                print_rainbow "────────────────────────────────────────"
                service cron restart >/dev/null 2>&1
                ;;
            2)
                echo -e "SHELL=/bin/sh\nPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\n*/10 * * * * root /usr/bin/malhware" >/etc/cron.d/autokill
                clear
                print_rainbow "────────────────────────────────────────"
                echo -e "${orange}│${neutral}"
                echo -e "${orange}│${neutral}      AutoKill: Every 10 Minutes"
                echo -e "${orange}│${neutral}"
                print_rainbow "────────────────────────────────────────"
                service cron restart >/dev/null 2>&1
                ;;
            3)
                echo -e "SHELL=/bin/sh\nPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\n*/15 * * * * root /usr/bin/malhware" >/etc/cron.d/autokill
                clear
                print_rainbow "────────────────────────────────────────"
                echo -e "${orange}│${neutral}"
                echo -e "${orange}│${neutral}      AutoKill: Every 15 Minutes"
                echo -e "${orange}│${neutral}"
                print_rainbow "────────────────────────────────────────"
                service cron restart >/dev/null 2>&1
                ;;
            4)
                if [ ! -f /etc/cron.d/autokill ]; then
                    clear
                    print_rainbow "────────────────────────────────────────"
                    echo -e "${orange}│${neutral}"
                    echo -e "${orange}│${neutral} AutoKill Already ${red}Disabled${neutral}"
                    echo -e "${orange}│${neutral}"
                    print_rainbow "────────────────────────────────────────"
                    return
                fi
                rm -f /etc/cron.d/autokill
                clear
                print_rainbow "────────────────────────────────────────"
                echo -e "${orange}│${neutral}"
                echo -e "${orange}│${neutral}      AutoKill ${red}Disabled${neutral}"
                echo -e "${orange}│${neutral}"
                print_rainbow "────────────────────────────────────────"
                service cron restart >/dev/null 2>&1
                return
                ;;
            x | X)
                clear
                return
                ;;
            *)
                echo "Invalid choice. Please try again."
                return
                ;;
            esac

        }


display_ssh_menu() {
    clear
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "       ${green}.::::. SSH MANAGER .::::.${neutral}"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    echo -e "    ${green}1.${neutral} Create SSH OVPN Account"
    echo -e "    ${green}2.${neutral} Delete SSH OVPN Account"
    echo -e "    ${green}3.${neutral} Renew SSH OVPN Account"
    echo -e "    ${green}4.${neutral} Check SSH OVPN Account Login"
    echo -e "    ${green}5.${neutral} List SSH OVPN Members"
    echo -e "    ${green}6.${neutral} Change SSH OVPN Account Limit"
    echo -e "    ${green}7.${neutral} Lock SSH OVPN Account"
    echo -e "    ${green}8.${neutral} Unlock SSH OVPN Account"
    echo -e "    ${green}9.${neutral} SSH OVPN Account Details"
    echo -e "    ${green}10.${neutral} Autokill SSH OVPN Account"
    echo -e "    ${green}11.${neutral} Create Trial SSH OVPN Account"
    echo -e "    ${green}x.${neutral} Exit SSH Manager"
    echo -e "${orange}─────────────────────────────────────────${neutral}"
    print_rainbow "─────────────────────────────────────────"
    read -p " Enter your choice 'x' to exit: " ssh_choice

    case $ssh_choice in
    1) cleam ;;
    2) dellssh ;;
    3) renewssh ;;
    4) checkssh ;;
    5) member_ssh ;;
    6) change_ip_ssh ;;
    7) lock_ssh ;;
    8) unlock_ssh ;;
    9) detailssh ;;
    10) autokill_ssh ;;
    11) trialssh ;;
    x | X)
        echo -e ""
        echo -e "   ${green}Thank you for using our services.${neutral}"
        sleep 2
        menu  
        ;;
    *)
        echo -e "   ${red}Invalid option. Please try again.${neutral}"
        sleep 2
        display_ssh_menu
        ;;
    esac
}

display_ssh_menu
