#!/bin/bash
clear

domain=$(cat /root/domain)
tmp_folder="/tmp"
tmp_file="${tmp_folder}/user_data.json"

# Variabel API
API_URL="https://${domain}/api/users"
TOKEN=$(cat /root/token.json | jq -r .access_token)

# Function to convert expiration timestamp to human-readable format
convert_expiration() {
  timestamp="${1}"
  if [ "${timestamp}" == "null" ]; then
    echo "Always ON"
  else
    date -d "@${timestamp}" '+%Y-%m-%d %H:%M:%S'
  fi
}

# Function to fetch user data and save it to a temporary file
fetch_and_save_data() {
  curl -s -X 'GET' \
    "${API_URL}" \
    -H 'accept: application/json' \
    -H "Authorization: Bearer ${TOKEN}" > "${tmp_file}"
}

# Check if the temporary file exists and is not older than 5 minutes
if [ -f "${tmp_file}" ] && [ "$(find "${tmp_file}" -mmin +5)" ]; then
  echo "Using cached user data..."
else
  echo "Fetching user data..."
  fetch_and_save_data
fi

# Check if the API request was successful
if [ $? -ne 0 ]; then
  echo "Error fetching data from the API"
  exit 1
fi

# Check if the response is valid JSON
if ! jq '.' "${tmp_file}" > /dev/null 2>&1; then
  echo "Invalid JSON response from the API"
  exit 1
fi

# Extract relevant information and format the output
echo "No.   Username                Protocol     Expires At"
echo "----- ------------------------ ------------ ---------------------"

# Loop through the users and print the information with line numbers
count=1
while IFS= read -r row; do
  username=$(jq -r '.username' <<< "${row}")
  expires_at=$(jq -r '.expire' <<< "${row}")
  protocol=$(jq -r '.proxies | keys_unsorted[0]' <<< "${row}" | sed 's/shadowsocks/ss/')

  expires_at_human=$(convert_expiration "${expires_at}")

  printf "%-5s %-24s %-13s %s\n" "${count}" "${username}" "${protocol}" "${expires_at_human}"
  ((count++))
done <<< "$(jq -c '.users[]' "${tmp_file}")"

# User input for user selection
echo "Pilih pengguna yang akan dihapus (Masukkan nomor yang sesuai):" read user_number

# Validate user input
if [[ ! $user_number =~ ^[0-9]+$ ]]; then
  echo "Masukan tidak valid. Silakan masukkan nomor pilihan yang benar."
  exit 1
fi

# Fetch selected user information
selected_user=$(jq -c --argjson user_number "$user_number" '.users[$user_number - 1]' "${tmp_file}")

# Check if the selected user exists
if [[ $selected_user == "null" ]]; then
  echo "User not found. Please enter a valid number."
  exit 1
fi

# Display selected user information
echo "Kamu memilih user $user_number:"
echo "Username: $(jq -r '.username' <<< "${selected_user}")"
echo "Protocol: $(jq -r '.proxies | keys_unsorted[0]' <<< "${selected_user}" | sed 's/shadowsocks/ss/')"
echo "Expires At: $(convert_expiration "$(jq -r '.expire' <<< "${selected_user}")")"

# Ask for confirmation before deleting the user
echo "Apa kamu ingin menghapus user ini? (y/n):" read confirmation

if [[ "$confirmation" == "y" || "$confirmation" == "Y" ]]; then
  # Perform user deletion
  username_to_delete=$(jq -r '.username' <<< "${selected_user}")
  curl -s -X 'DELETE' \
    "https://${domain}/api/user/${username_to_delete}" \
    -H 'accept: application/json' \
    -H "Authorization: Bearer ${TOKEN}"
rm -r /var/www/html/oc-${username_to_delete}.conf
  echo "User ${username_to_delete} telah berhasil dihapus."
else
  echo "Operasi hapus user telah dibatalkan"
fi
