---
# Pyenv requires compilers and build tools

# Debian 9
- name: Installing build-essential and pyenv dependencies
  apt:
    update_cache: yes
    state: present
    name:
      - build-essential
      - checkinstall
      - libreadline-gplv2-dev
      - libncursesw5-dev
      - libssl-dev
      - libsqlite3-dev
      - tk-dev
      - libgdbm-dev
      - libc6-dev
      - libbz2-dev
      - libffi-dev
  when: ansible_os_family == "Debian" and ansible_distribution_major_version == "9"

# Debian 10
- name: Installing build-essential and pyenv dependencies
  apt:
    update_cache: yes
    state: present
    name:
      - build-essential
      - libreadline-gplv2-dev
      - libncursesw5-dev
      - libssl-dev
      - libsqlite3-dev
      - tk-dev
      - libgdbm-dev
      - libc6-dev
      - libbz2-dev
      - libffi-dev
  when: ansible_os_family == "Debian" and ansible_distribution_major_version == "10"

# Debian 12
- name: Installing build-essential and pyenv dependencies
  apt:
    update_cache: yes
    state: present
    name:
      - build-essential
      - libreadline-dev
      - libncursesw5-dev
      - libssl-dev
      - libsqlite3-dev
      - tk-dev
      - libgdbm-dev
      - libc6-dev
      - libbz2-dev
      - libffi-dev
  when: ansible_os_family == "Debian" and ansible_distribution_major_version == "12"

# Install pyenv using git clone
- name: Installing pyenv using git clone
  git:
    repo: https://github.com/pyenv/pyenv.git
    dest: /usr/local/lib/pyenv
    force: yes
    depth: 1

# Set users and permissions
# There is also a files/bin/pyenv-fix-permissions.sh that mirror the below
# which you can run manually after you install a new version (pyenv sets mask and ignores setfacl)
- file: 'path=/usr/local/lib/pyenv owner={{ superuser }} group={{ supergroup }} state=directory recurse=yes mode=2775'
- command: find /usr/local/lib/pyenv -type d -exec chmod 2775 {} \;
- command: setfacl -R -d -m user::rwx,group::rwx /usr/local/lib/pyenv

# Adjust git to allow alternate perms on /usr/local/lib/pyenv
# If you don't do this, and run playbook again it errors on
# FAILED! => {"changed": false, "msg": "Failed to set a new url https://github.com/pyenv/pyenv.git for origin:  fatal: detected dubious ownership in repository at '/usr/local/lib/pyenv'\nTo add an exception for this directory, call:\n\n\tgit config --global --add safe.directory /usr/local/lib/pyenv\n"}
- name: Adjust git to allow alternate perms on /usr/local/lib/pyenv
  ansible.builtin.shell:
    cmd: git config --global --add safe.directory /usr/local/lib/pyenv
