#!/bin/bash
clear

# Value yang dibutuhkan
tanggal=$(date +"%m-%d-%Y")
tanggal2=$(date +"%m%d%Y")
waktu=$(date +"%T" | tr -d ':')
InputPass=$(cat /root/passbackup)

# Value Warna
green='\e[0;32m'
NC='\e[0m'
green() { echo -e "\\033[32;1m${*}\\033[0m"; }

# Authentication
nama=$(cat /root/nama)

# Configuration file exists, load values
source "/root/telegram_config.conf"

# Function to print a stylish header
print_header() {
    echo "**************************************************"
    echo "*                                                *"
    echo "*          Backup and Restore Options Menu        *"
    echo "*                                                *"
    echo "**************************************************"
    echo ""
}

# Function to restore data from Telegram backup
restore_from_telegram() {
    clear
    print_header
if [[ ! -f "/root/telegram_config.conf" ]]; then
    # Bot token and user ID not set, prompt user to enter them
    echo "Bot token and user ID are not set. Please enter your bot token and user ID."

    read -rp "Enter your Telegram bot token: " botToken
    read -rp "Enter your Telegram user ID: " chatId

    # Save the configuration
    echo "botToken=$botToken" > "/root/telegram_config.conf"
    echo "chatId=$chatId" >> "/root/telegram_config.conf"

    echo "Configuration saved successfully. You can now run the backup script."
    exit 0
fi

    echo "Restoring from Telegram..."

    # Ganti FILE_ID dengan file_id yang ingin kamu unduh
    FILE_ID=$(grep '^File ID:' /root/file_id.txt | awk '{print $3}' | tail -n 1)

    # Dapatkan tautan unduhan menggunakan curl
    FILE_URL=$(curl -s "https://api.telegram.org/bot$botToken/getFile?file_id=$FILE_ID" | jq -r .result.file_path)

    # Ganti FILE_NAME sesuai keinginan Anda
    FILE_NAME=$(grep '^###' /root/file_id.txt | cut -d' ' -f2- | tail -n 1)

    # Unduh file menggunakan tautan
    curl -o /root/${FILE_NAME}.zip "https://api.telegram.org/file/bot$botToken/$FILE_URL"
    # Periksa apakah unduhan berhasil
	if [ $? -eq 0 ]; then
  echo "Download successful. Proceeding with unzip..."
  # Proses restorasi atau operasi lain yang perlu dilakukan setelah mengunduh
  unzip -P ${InputPass} /root/${FILE_NAME}.zip
  # Periksa apakah unzip berhasil
  if [ $? -eq 0 ]; then
    echo "Unzip successful. Restore process complete."
  else
    echo "Error: Unzip failed."
  fi
else
  echo "Error: Download failed."
fi
# Proses ekstrak
cd /root/backup
cp *.conf /var/lib/marzban/
cp -f db.sqlite3 /var/lib/marzban/db.sqlite3
cp -f html /var/www/
cp -f marzban /opt/
cp -f xray_config.json /var/lib/marzban/xray_config.json
cd
sleep 3
marzban restart
echo "Tahap restorasi telah selesai"
}


# Function to backup data and send to Telegram
backup_and_send_telegram() {
    clear
    print_header
# Check if bot token and user ID are already set
if [[ ! -f "/root/telegram_config.conf" ]]; then
    # Bot token and user ID not set, prompt user to enter them
    echo "Bot token and user ID are not set. Please enter your bot token and user ID."

    read -rp "Enter your Telegram bot token: " botToken
    read -rp "Enter your Telegram user ID: " chatId

    # Save the configuration
    echo "botToken=$botToken" > "/root/telegram_config.conf"
    echo "chatId=$chatId" >> "/root/telegram_config.conf"

    echo "Configuration saved successfully. You can now run the backup script."
    exit 0
fi

    green='\e[0;32m'
    NC='\e[0m'
    green() { echo -e "\\033[32;1m${*}\\033[0m"; }

    echo -e "Memulai Backup harian"
    InputPass=$(cat /root/passbackup)
    sleep 1
    echo -e "[ ${green}INFO${NC} ] Processing... "
    mkdir -p /root/backup
    sleep 1

	cp -r /opt/marzban /root/backup/
	cp /var/lib/marzban/xray_config.json /root/backup/
	cp /var/lib/marzban/max_ips.conf /root/backup/
	cp /var/lib/marzban/db.sqlite3 /root/backup/
	cp -r /var/www/html/ /root/backup/
	cp /var/lib/marzban/akun-trojan.conf /root/backup/
	cp /var/lib/marzban/akun-vless.conf /root/backup/
	cp /var/lib/marzban/akun-vmess.conf /root/backup/
	cp /var/lib/marzban/akun-ss.conf /root/backup/
    cd /root
    zip -rP ${InputPass} ${nama}_${waktu}_${tanggal2}.zip backup

    ##############++++++++++++++++++++++++#############

    curdir="/root/${nama}_${waktu}_${tanggal2}.zip"
    echo "Sending $curdir to Telegram..."

    #Mengirim dokumen dan mendapatkan respons JSON
    response=$(curl -F chat_id=$chatId -F document=@$curdir https://api.telegram.org/bot$botToken/sendDocument)

    # Ekstrak file_id dari respons JSON
    file_id=$(echo "$response" | jq -r '.result.document.file_id')

    # Menyimpan file_id ke file
    echo "### ${nama}_${waktu}_${tanggal}" >> /root/file_id.txt
    echo "File ID: $file_id" >> /root/file_id.txt
    echo "Server telah berhasil backup data pada tanggal $tanggal pukul $waktu." >> "/root/log-backup.txt"
    sleep 1
    rm -rf /root/backup &> /dev/null
    rm -f $curdir &> /dev/null
    profile
}

# Function to run daily backup (called by cron)
daily_backup() {
    print_header
    clear
    echo "Running Daily Backup..."
    backup_and_send_telegram
    echo "Daily Backup Complete."
}

# Function to run weekly backup (called by cron)
weekly_backup() {
    print_header
    clear
    echo "Running Weekly Backup..."
    backup_and_send_telegram
    echo "Weekly Backup Complete."
}

# Function to run monthly backup (called by cron)
monthly_backup() {
    print_header
    clear
    echo "Running Monthly Backup..."
    backup_and_send_telegram
    echo "Monthly Backup Complete."
}

# Function to set backup timer
set_backup_timer() {
    print_header
    clear
    echo "Setting Backup Timer..."
    echo "1. Set Daily Backup Timer"
    echo "2. Set Weekly Backup Timer"
    echo "3. Set Monthly Backup Timer"
    echo "4. Back to Main Menu"
    read -rp "Enter your choice (1-4): " choice

    case $choice in
        1)
            echo "Enter daily backup time in 24-hour format (HH:MM):"
            read -rp "Example: 02:00 for 2 AM - " daily_backup_time
            # Parse the input time
            hour=$(echo "$daily_backup_time" | cut -d: -f1)
            minute=$(echo "$daily_backup_time" | cut -d: -f2)
            echo "Setting up daily backup at $daily_backup_time..."
            (crontab -l 2>/dev/null; echo "$minute $hour * * * /usr/bin/backup daily") | crontab -
            ;;
        2)
            echo "Enter weekly backup day (0-6, Sunday to Saturday):"
            read -rp "Example: 1 for Monday - " weekly_backup_day
            echo "Enter weekly backup time in 24-hour format (HH:MM):"
            read -rp "Example: 02:00 for 2 AM - " weekly_backup_time
            # Parse the input time
            hour=$(echo "$weekly_backup_time" | cut -d: -f1)
            minute=$(echo "$weekly_backup_time" | cut -d: -f2)
            echo "Setting up weekly backup on day $weekly_backup_day at $weekly_backup_time..."
            (crontab -l 2>/dev/null; echo "$minute $hour * * $weekly_backup_day /usr/bin/backup weekly") | crontab -
            ;;
        3)
            echo "Enter monthly backup day of the month (1-31):"
            read -rp "Example: 1 for the 1st day - " monthly_backup_day
            echo "Enter monthly backup time in 24-hour format (HH:MM):"
            read -rp "Example: 02:00 for 2 AM - " monthly_backup_time
            # Parse the input time
            hour=$(echo "$monthly_backup_time" | cut -d: -f1)
            minute=$(echo "$monthly_backup_time" | cut -d: -f2)
            echo "Setting up monthly backup on day $monthly_backup_day at $monthly_backup_time..."
            (crontab -l 2>/dev/null; echo "$minute $hour $monthly_backup_day * * /usr/bin/backup monthly") | crontab -
            ;;
        4)
            return
            ;;
        *)
            echo "Invalid choice. Exiting..."
            exit 1
            ;;
    esac

    echo "Backup timer set up successfully."
}
# Function to remove backup timer
remove_backup_timer() {
    print_header
    clear
    echo "Removing Backup Timer..."
    echo "1. Remove Daily Backup Timer"
    echo "2. Remove Weekly Backup Timer"
    echo "3. Remove Monthly Backup Timer"
    echo "4. Back to Main Menu"
    read -rp "Enter your choice (1-4): " choice

    case $choice in
        1)
            echo "Removing daily backup timer..."
            (crontab -l 2>/dev/null | grep -v "/usr/bin/backup daily") | crontab -
            ;;
        2)
            echo "Removing weekly backup timer..."
            (crontab -l 2>/dev/null | grep -v "/usr/bin/backup weekly") | crontab -
            ;;
        3)
            echo "Removing monthly backup timer..."
            (crontab -l 2>/dev/null | grep -v "/usr/bin/backup monthly") | crontab -
            ;;
        4)
            return
            ;;
        *)
            echo "Invalid choice. Exiting..."
            exit 1
            ;;
    esac

    echo "Backup timer removed successfully."
}

# Main menu
# Main menu
while :; do
    print_header
    echo "Main Menu:"
    echo "1. Backup and Send to Telegram"
    echo "2. Set Backup Timer"
    echo "3. Remove Backup Timer"
    echo "4. Restore from Telegram"
    echo "5. Exit"
    read -rp "Enter your choice (1-5): " choice

    case $choice in
        1)
            backup_and_send_telegram
            ;;
        2)
            set_backup_timer
            ;;
        3)
            remove_backup_timer
            ;;
        4)
            restore_from_telegram
            ;;
        5)
            exit 0
            ;;
        *)
            echo "Invalid choice. Try again."
            ;;
    esac
done
}
