%system_python python2
%python_for_executables python3

##### common functionality #####

%_python_sysconfig_path() %([ -x %1 ] && RPM_BUILD_ROOT="%{buildroot}" %1 -c "import sysconfig as s; print(s.get_paths().get('%2'))" || echo "!!_{%1}_not_installed_!!")
%_python_sysconfig_var()  %([ -x %1 ] && RPM_BUILD_ROOT="%{buildroot}" %1 -c "import sysconfig as s; print(s.get_config_var('%2'))"  || echo "!!_{%1}_not_installed_!!")

%_rec_macro_helper %{lua:
    rpm.define("_rec_macro_helper %{nil}")
    function expand_macro(name, args)
        local pflavor = rpm.expand("%python_flavor")
        local args   = args and rpm.expand(args) or ""
        print(rpm.expand("%{" .. pflavor .. "_" .. name .. " " .. args .."}"))
    end
}

# put wheels into python_expand shuffled wheeldir by default
%_pyproject_wheeldir ./build

# put flavor-agnostic wheels into a common dir. Dist is the default destination of pytnon -m build
%_pyproject_anywheeldir ./dist

%pyproject_wheel_args \\\
  --verbose --progress-bar off --disable-pip-version-check \\\
  %{?py_setup_args:--build-option %{py_setup_args}} \\\
  --use-pep517 --no-build-isolation \\\
  --no-deps \\\
  --wheel-dir %{_pyproject_wheeldir}

%pyproject_install_args \\\
  --verbose --progress-bar off --disable-pip-version-check \\\
  --root %{buildroot} \\\
  --no-compile \\\
  --ignore-installed --no-deps \\\
  --no-index --find-links %{_pyproject_wheeldir}

##### fedora compatibility #####

%py_setup setup.py
%py_shbang_opts -s

##### non-standard binary suffixes for flavors #####

%_pypy3_bin_suffix   pp%{pypy3_version}


##### preferred configuration #####

%python_sitelib          %{_python_sysconfig_path %{expand:%__%{python_flavor}} purelib}
%python_sitearch         %{_python_sysconfig_path %{expand:%__%{python_flavor}} platlib}
%python_version          %{_python_sysconfig_var  %{expand:%__%{python_flavor}} py_version_short}
%python_version_nodots   %{_python_sysconfig_var  %{expand:%__%{python_flavor}} py_version_nodot}

%python_sysconfig_path()        %{_python_sysconfig_path %{expand:%__%{python_flavor}} %1}
%python_sysconfig_var()         %{_python_sysconfig_var  %{expand:%__%{python_flavor}} %1}

%python_prefix                  %{_rec_macro_helper}%{lua:expand_macro("prefix")}
%python_bin_suffix              %{_rec_macro_helper}%{lua:expand_macro("bin_suffix")}
%python_provides                %{_rec_macro_helper}%{lua:expand_macro("provides")}


%python_alternative()           %{_rec_macro_helper}%{lua:expand_macro("alternative", "%**")}
%python_install_alternative()   %{_rec_macro_helper}%{lua:expand_macro("install_alternative", "%**")}
%python_uninstall_alternative() %{_rec_macro_helper}%{lua:expand_macro("uninstall_alternative", "%**")}
%python_libalternatives_reset_alternative() %{_rec_macro_helper}%{lua:expand_macro("reset_alternative", "%**")}

# this is by convention hardcoded python2
%py_ver  %(python -c "import sys; v=sys.version_info[:2]; print '%%d.%%d'%%v" 2>/dev/null || echo PYTHON-NOT-FOUND)

##### Python dependency generator macros #####

# === Macros for Build/Requires tags using Python dist tags ===
# - https://fedoraproject.org/wiki/Changes/Automatic_Provides_for_Python_RPM_Packages

# Converts Python dist name to a canonical format
%python_dist_name() %{lua:\
        name = rpm.expand("%{?1:%{1}}");\
        canonical = string.gsub(string.lower(name), "[^%w%.]+", "-");\
        print(canonical);\
}

# Creates Python 2 dist tag(s) after converting names to canonical format
#   Needs to first put all arguments into a list, because invoking a different
#   macro (%python_dist_name) overwrites them
%python2_dist() %{lua:\
        args = {}\
        arg = 1\
        while (true) do\
                name = rpm.expand("%{?" .. arg .. ":%{" .. arg .. "}}");\
                if (name == nil or name == '') then\
                        break\
                end\
                args[arg] = name\
                arg = arg + 1\
        end\
        for arg, name in ipairs(args) do\
                canonical = rpm.expand("%python_dist_name " .. name);\
                print("python" .. rpm.expand("%python2_version") .. "dist(" .. canonical .. ") ");\
        end\
}

# Creates Python 3 dist tag(s) after converting names to canonical format
#   Needs to first put all arguments into a list, because invoking a different
#   macro (%python_dist_name) overwrites them
%python3_dist() %{lua:\
        args = {}\
        arg = 1\
        while (true) do\
                name = rpm.expand("%{?" .. arg .. ":%{" .. arg .. "}}");\
                if (name == nil or name == '') then\
                        break\
                end\
                args[arg] = name\
                arg = arg + 1\
        end\
        for arg, name in ipairs(args) do\
                canonical = rpm.expand("%python_dist_name " .. name);\
                print("python" .. rpm.expand("%python3_version") .. "dist(" .. canonical .. ") ");\
        end\
}

# === Macros to control dependency generator ===
# - https://fedoraproject.org/wiki/Changes/EnablingPythonGenerators
%python_enable_dependency_generator() \
%global __pythondist_requires %{_rpmconfigdir}/pythondistdeps.py --requires \
%{nil}

##### Python Unittest macros #####

%pyunittest(+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-=) \
%python_flavored_alternatives \
%{lua:\
    local args = rpm.expand("%**"); \
    local broot = rpm.expand("%buildroot"); \
    local intro = "%{python_expand PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}" .. broot .. "%{$python_sitelib} PYTHONDONTWRITEBYTECODE=1 $python -m unittest "; \
    print(rpm.expand(intro .. args .. "}")) \
}

%pyunittest_arch(+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-=) \
%python_flavored_alternatives \
%{lua:\
    local args = rpm.expand("%**"); \
    local broot = rpm.expand("%buildroot"); \
    local intro = "%{python_expand PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}" .. broot .. "%{$python_sitearch} PYTHONDONTWRITEBYTECODE=1 $python -m unittest "; \
    print(rpm.expand(intro .. args .. "}")) \
}

##### Pytest macros #####

%pytest(+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-=) \
%python_flavored_alternatives \
%{lua:\
    local args = rpm.expand("%**"); \
    local broot = rpm.expand("%buildroot"); \
    local intro = "%{python_expand PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}" .. broot .. "%{$python_sitelib} PYTHONDONTWRITEBYTECODE=1 "; \
    local ignore_build = "--ignore=_build." .. rpm.expand("%pythons"):gsub("%s+", " --ignore=_build."); \
    intro = intro .. "pytest-%{$python_bin_suffix} " .. ignore_build .. " -v "; \
    print(rpm.expand(intro .. args .. "}")) \
}

%pytest_arch(+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-=) \
%python_flavored_alternatives \
%{lua:\
    local args = rpm.expand("%**"); \
    local broot = rpm.expand("%buildroot"); \
    local intro = "%{python_expand PYTHONPATH=${PYTHONPATH:+$PYTHONPATH:}" .. broot .. "%{$python_sitearch} PYTHONDONTWRITEBYTECODE=1 "; \
    local ignore_build = "--ignore=_build." .. rpm.expand("%pythons"):gsub("%s+", " --ignore=_build."); \
    intro = intro .. "pytest-%{$python_bin_suffix} " .. ignore_build .. " -v "; \
    print(rpm.expand(intro .. args .. "}")) \
}

##### Find language files #####

%python_find_lang() \
%find_lang %{**} \
langfile=%{?2}%{!?2:%1.lang} \
%{python_expand # \
grep -v 'python.*site-packages' ${langfile} > %{$python_prefix}-${langfile} \
grep -F %{$python_sitelib} ${langfile} >> %{$python_prefix}-${langfile} \
} \
%{nil}
