#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Script untuk menjalankan bot Telegram sebagai systemd service.
"""

import os
import sys
import logging
from pathlib import Path

# Dapatkan direktori script saat ini
SCRIPT_DIR = Path(__file__).parent.absolute()

# Template untuk file service systemd
SYSTEMD_SERVICE_TEMPLATE = """[Unit]
Description=Telegram File Download Bot
After=network.target

[Service]
Type=simple
User={user}
WorkingDirectory={work_dir}
ExecStart={python_path} {bot_script}
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
"""

def create_systemd_service():
    """Membuat file service systemd untuk bot."""
    # Konfigurasi
    user = os.environ.get("USER", "ubuntu")
    python_path = sys.executable
    bot_script = SCRIPT_DIR / "bot.py"
    service_file = SCRIPT_DIR / "telegram_file_download_bot.service"
    
    # Buat file service
    service_content = SYSTEMD_SERVICE_TEMPLATE.format(
        user=user,
        work_dir=SCRIPT_DIR,
        python_path=python_path,
        bot_script=bot_script
    )
    
    with open(service_file, "w") as f:
        f.write(service_content)
    
    print(f"File service systemd dibuat di: {service_file}")
    print("\nUntuk menginstal service, jalankan perintah berikut sebagai root:")
    print(f"sudo cp {service_file} /etc/systemd/system/")
    print("sudo systemctl daemon-reload")
    print("sudo systemctl enable telegram_file_download_bot.service")
    print("sudo systemctl start telegram_file_download_bot.service")
    print("\nUntuk memeriksa status service:")
    print("sudo systemctl status telegram_file_download_bot.service")
    
    return service_file

if __name__ == "__main__":
    create_systemd_service()
