#!/bin/bash

# === Warna ===
CYAN='\033[0;36m'
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'

config_file="/root/backup_config.conf"
restore_dir="/var/lib/marzban"
backup_dir="/root"

# Cek file config
if [ ! -f "$config_file" ]; then
    echo -e "${RED}File Backup tidak ditemukan. Jalankan skrip backup dan setup BOT terlebih dahulu.${NC}"
    exit 1
fi

source "$config_file"

# Cari file ZIP backup secara otomatis
latest_zip=$(ls -t ${backup_dir}/*-backupdata.zip 2>/dev/null | head -n 1)

if [[ -z "$latest_zip" ]]; then
    echo -e "${RED}File backup tidak ditemukan di ${backup_dir}${NC}"
    exit 1
fi

echo -e "${CYAN}➤ File Backup ditemukan: $latest_zip${NC}"
read -p "$(echo -e "${YELLOW}➽ Lanjutkan proses restore? (y/N): ${NC}")" confirm

if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
    echo -e "${YELLOW}Proses restore dibatalkan.${NC}"
    exit 0
fi

# Ekstrak db.sqlite3 ke lokasi sementara
temp_dir=$(mktemp -d)
unzip -j "$latest_zip" -d "$temp_dir" > /dev/null 2>&1

if [ ! -f "$temp_dir/db.sqlite3" ]; then
    echo -e "${RED}File db.sqlite3 tidak ditemukan di dalam ZIP.${NC}"
    exit 1
fi

# Backup file lama jika ada
if [ -f "${restore_dir}/db.sqlite3" ]; then
    cp "${restore_dir}/db.sqlite3" "${restore_dir}/db.sqlite3.bak_$(date +%s)"
fi

# Ganti file lama dengan yang baru
mv "$temp_dir/db.sqlite3" "${restore_dir}/db.sqlite3"
chmod 644 "${restore_dir}/db.sqlite3"
chown root:root "${restore_dir}/db.sqlite3"

# Hapus direktori sementara
rm -rf "$temp_dir"

# Kirim notifikasi Telegram
CLIENT_NAME=$(hostname)
IP_ADDRESS=$(curl -s ifconfig.me)

curl -s -X POST "https://api.telegram.org/bot${BOT_API}/sendMessage" \
    -d chat_id="${CHAT_ID}" \
    -d parse_mode="HTML" \
    -d text=$'=================================\n ✅ <b>Restore Database Succeed</b>\n=================================\n◈ Client : <code>'"$CLIENT_NAME</code>"$'\n◈ IP : <code>'"$IP_ADDRESS</code>"$'\n◈ File : <code>'"$(basename $latest_zip)</code>"$'\n\n➣ Owner By : Admin SN\n=================================\n'

echo -e "${GREEN}Restore berhasil dilakukan dan notifikasi dikirim ke Telegram.${NC}"
