import os
import calendar
import tkinter as tk
from tkinter import messagebox
from tkcalendar import Calendar

def schedule_script(script, date):
    # Convert the selected date to cron format (every day at 12:00 PM for example)
    cron_time = f"{date[2]} {date[1]} {date[0]} 12 * *"  # Run at 12:00 noon every selected day
    
    # Get the full path of the script (absolute path)
    script_path = os.path.abspath(script)
    
    # Create the cron job as a string (user's crontab)
    cron_job = f"{cron_time} {script_path}\n"

    try:
        # Add the cron job to the user's crontab
        # Use crontab -l to list the current user's cron jobs and then pipe them into crontab
        current_cron = os.popen("crontab -l").read()  # Get current user's cron jobs
        if cron_job not in current_cron:
            os.system(f"(echo \"{current_cron}\"; echo \"{cron_job}\") | crontab -")
            messagebox.showinfo("Scheduled", f"Scheduled {script} for {date[0]}-{date[1]}-{date[2]}")
        else:
            messagebox.showwarning("Already Scheduled", f"{script} is already scheduled for {date[0]}-{date[1]}-{date[2]}.")
    except Exception as e:
        messagebox.showerror("Error", f"Failed to schedule cron job: {e}")

def on_date_selected(event):
    # Get the selected date from the calendar widget
    selected_date = event.widget.selection_get()
    
    # Extract day, month, and year from selected date
    year, month, day = selected_date.split('-')

    script = script_var.get()  # Get selected script
    schedule_script(script, (year, month, day))

def create_ui():
    root = tk.Tk()
    root.title("Schedule Bash Script")

    # Script selection dropdown
    global script_var
    script_var = tk.StringVar()
    script_var.set("script1.sh")  # Default selection
    script_dropdown = tk.OptionMenu(root, script_var, "script1.sh", "script2.sh", "script3.sh", "script4.sh")
    script_dropdown.pack()

    # Calendar widget
    cal = Calendar(root, selectmode="day", year=2025, month=10, day=1)
    cal.pack()

    # Schedule button
    schedule_button = tk.Button(root, text="Schedule Script", command=lambda: on_date_selected(cal))
    schedule_button.pack()

    root.mainloop()

if __name__ == "__main__":
    create_ui()
