"""
Shell Script Class
"""

import os
import stat
import tempfile


class ShellScript:
    """
    Generate a shell script
    """

    def __init__(self, keepfiles, gitinfo, save_shell_script, shell_script_name):
        self.keepfiles = keepfiles
        self.gitinfo = gitinfo
        self.save_shell_script = save_shell_script
        self.shell_script_name = shell_script_name
        self.script = []
        self.generate_script()
        if not save_shell_script:
            _, self.shell_script_name = tempfile.mkstemp(suffix=".sh")

        self.save_script()

    def generate_script(self):
        self.script.extend(
            [
                "#! /bin/env bash",
                "",
                "####################################################################",
                "# This script was generated by git-repo-move! Star it on Github ⭐ #",
                "####################################################################",
                "",
                "# Create a new branch (delete if exists)",
                self.gitinfo.create_new_branch_cmd(),
                "",
            ]
        )
        if self.keepfiles.common_path:
            self.script.extend(
                [
                    f"# There's a common path for the selected files: {self.keepfiles.common_path}",
                    "# As an optimization we'll run subdirectory-filter on the common path first",
                    f"git filter-branch --force --prune-empty --subdirectory-filter {self.keepfiles.common_path}",
                    "",
                ]
            )

        keepfiles_cmds = ";\n    ".join(self.keepfiles.commands)
        self.script.extend(
            [
                "# The tree-filter flag will run a command on every commit",
                "# Let's run a command to move all the files we care about to a safe location",
                f'git filter-branch --force --prune-empty --tree-filter "{keepfiles_cmds} || true"',
                "",
                "# The subdirectory-filter flag filters everything not in the specified folder",
                f"git filter-branch --force --prune-empty --subdirectory-filter {self.keepfiles.working_dir}",
                "",
                "# Add a new remote and push the branch",
                self.gitinfo.add_new_remote_cmd(),
                self.gitinfo.push_branch_to_remote_cmd(),
                "",
                "# Let's remove the remote since we don't need it anymore",
                self.gitinfo.remove_new_remote_cmd(),
            ]
        )

    def save_script(self):
        with open(self.shell_script_name, "w") as file:
            for line in self.script:
                file.write(line)
                file.write("\n")

        # Mark the script as executable
        st = os.stat(self.shell_script_name)
        os.chmod(self.shell_script_name, st.st_mode | stat.S_IEXEC)

    def execute(self):
        return os.system(f"./{self.shell_script_name}")
