import os
import subprocess
import sys

def main():
    mydir = os.path.dirname(__file__)

    # Define the absolute path to the prep script
    prep_script = os.path.join(mydir, 'prep 1 font.sh')

    # Activate python environment
    env_activate = os.path.join(mydir, '.env/bin/activate')
    subprocess.run(['source', env_activate], shell=True, check=True)

    # Move orphans before we do anything else
    orphans_script = os.path.join(mydir, 'orphans.py')
    subprocess.run(['python3', orphans_script], check=True)

    # Check if the prep script exists
    if not os.path.isfile(prep_script):
        print(f"Prep script not found: {prep_script}")
        sys.exit(1)

    # Ensure the prep script is executable
    os.chmod(prep_script, 0o755)

    # Check if the prep script is executable
    if not os.access(prep_script, os.X_OK):
        print(f"Prep script not executable: {prep_script}")
        sys.exit(1)

    # Define the absolute path to the font_files directory
    font_files_dir = os.path.join(mydir, 'font_files')

    # Check if the font_files directory exists
    if not os.path.isdir(font_files_dir):
        print(f"font_files directory not found: {font_files_dir}")
        sys.exit(1)

    # Iterate over each folder in font_files
    for folder in os.listdir(font_files_dir):
        folder_path = os.path.join(font_files_dir, folder)
        if os.path.isdir(folder_path):
            os.chdir(folder_path)
            subprocess.run(['zsh', prep_script], check=True)
            os.chdir('..')
        else:
            print(f"No such directory: {folder}")

if __name__ == '__main__':
    main()