"""
* Author: "PepDebian(peppermintosteam@proton.me)
*
* License: SPDX-License-Identifier: GPL-3.0-or-later
*
* Beta upgrade tool. 
"""
import os
import re
import subprocess
import shutil
import tkinter as tk
import ttkbootstrap as ttk
import upgradeconf

# setting up window
pepupdate = upgradeconf.bbstyle
pepupdate.resizable(False, False)
WINDOW_HEIGHT = 230
WINDOW_WIDTH = 370

# This will get the logged in user
gusr = os.getlogin()
spath = "/home/" + gusr



# Source things
fpath = "/etc/apt/sources.list"
text = "bullseye"
settext = "bookworm"


def setsource(fpath, text, settext, flags=0):
    """ Replace the source code names """
    with open(fpath,"r+") as file:
        file_contents = file.read()
        txt_pattern = re.compile(re.escape(text), flags)
        file_contents = txt_pattern.sub(settext, file_contents)
        file.seek(0)
        file.truncate()
        file.write(file_contents)


def movepins():
    """ Check if the Pins exists if they do move them
        to backup folder
    """
    pin_path = "/etc/apt/preferences.d/99pin-unstable"
    bkup_path= spath + '/pin_backup'
    if os.path.exists(pin_path):
        os.mkdir(bkup_path)
        print('Pin backup folder made')
        shutil.copy(pin_path, bkup_path)
        print('Pin file copied')
        os.remove(pin_path)
        print('Pin file deleted')
    else:
        pass

def upgrade_cmd():
    # Put the commands together
    set_terminal = 'xfce4-terminal -T \"Upgrade Peppermint" '
    call_bash = '-e \"bash -c '
    sudo_var = 'sudo apt '
    update_cmd = sudo_var + 'update'
    upgrade_cmd = sudo_var +  'upgrade'
    full_cmd = sudo_var + 'full-upgrade'
    clean_cmd = sudo_var + 'clean'
    remove_cmd = sudo_var + 'autoremove'
    reboot_cmd = sudo_var + 'shutdown -r now'
    installer_remove = sudo_var + 'remove calamares'
    installer_settings = sudo_var + 'remove calamares-settings-debian'
    xDaily = 'sudo xDaily'
    # Commands to run
    prep_go = (set_terminal +
            call_bash + "'" +
            update_cmd + ' && ' +
            upgrade_cmd + ' && ' +
            full_cmd  + "'" + '"'
            )

    final_go = (set_terminal +
                call_bash + "'" +
                clean_cmd + ' && ' +
                update_cmd + ' && ' +
                upgrade_cmd + ' && ' +
                full_cmd + ' && ' +
                remove_cmd + ' && ' +
                #reboot_cmd + ' && ' +
                installer_remove + ' && ' +
                installer_settings + ' && ' +
                xDaily + "'" + '"'
                )
    # Run the Commands in order
    subprocess.Popen(prep_go, shell=True)
    setsource(fpath, text, settext)
    movepins()
    subprocess.Popen(final_go, shell=True)





def center_screen():
    """ gets the coordinates of the center of the screen """
    screen_width = pepupdate.winfo_screenwidth()
    screen_height = pepupdate.winfo_screenheight()
    # Coordinates of the upper left corner of the window to make the window
    # appear in the center
    x_cordinate = int((screen_width / 2) - (WINDOW_WIDTH / 2))
    y_cordinate = int((screen_height / 2) - (WINDOW_HEIGHT / 2))
    pepupdate.geometry("{}x{}+{}+{}".format(WINDOW_WIDTH,
                   WINDOW_HEIGHT, x_cordinate, y_cordinate))
def ubase():
    """Check to see what base is being loaded"""
    if os.path.exists("/etc/devuan_version"):
        pepupdate.title(welconf.DEVUAN_TITLE)
        lpath = upgradeconf.devcandy
        l_g = tk.Label(pepupdate, image=lpath, width=128, height=128, borderwidth=0)
        l_g.grid(
            columnspan=2,
            row=0,
            column=0,
            ipadx=5,
            ipady=5,
            padx=5,
            pady=5)
    elif os.path.exists("/etc/debian_version"):
        pepupdate.title(upgradeconf.DEBIAN_TITLE)

# Set the window icon
pepupdate.tk.call('wm', 'iconphoto', pepupdate._w, tk.PhotoImage(
    file='/usr/share/pixmaps/peppermint-old.png'))


codename_label = ttk.Label(pepupdate, text="Enter the Codename to upgrade to:")
codename_label.place(x=10, y=20)

examples_label = ttk.Label(pepupdate, text='** For example: bookworm, bullseye,'
                                           ' stretch **', bootstyle="danger")
examples_label.place(x=10, y=80)

warning_label = ttk.Label(pepupdate, text='Make sure to backup your data!',
                                            bootstyle="warning")
warning_label.place(x=10, y=170)

code_value = tk.Text(pepupdate, height=1, width=25)
code_value.place(x=10, y=45)


btnsv = ttk.Button(
    pepupdate,
    text="Upgrade",
    cursor="hand2",
    bootstyle="light-outline",
    width=8,
    command=upgrade_cmd
    )
btnsv.place(x=10, y=110)

btncl = ttk.Button(
    pepupdate,
    text="Cancel",
    cursor="hand2",
    bootstyle="light-outline",
    width=8
    )
btncl.place(x=120, y=110)


ubase()
# call Center screen
center_screen()
# run the application
pepupdate.mainloop()
