# roles/calibre/tasks/main.yml requires calibre_via_python (to be True) before calling this script.

# Seems to work with just about any Linux (Fedora 18 on OLPC XO Laptops??) and deals with dependencies.
# BUT IS ARCH DEPENDENT: requires x86_64 or i686 as of early 2018.

- name: Download latest linux-installer.py from GitHub to calibre-installer.py
  get_url:
    url: "{{ calibre_src_url }}"
    dest: "{{ downloads_dir }}/calibre-installer.py"
    mode: 0755
    force: yes
    backup: yes
    timeout: "{{ download_timeout }}"
  register: calibre_download_output

# ALWAYS DEFINED, DESPITE get_url DOCUMENTATION CLAIM...
# - debug:
#     msg: "{{ calibre_download_output.src }}"
#
# DEFINED ONLY WHEN /opt/iiab/downloads/calibre-installer.py CHANGES
# - debug:
#    msg: "{{ calibre_download_output.backup_file }}"

# OOPS BAD IDEA: changes in https://github.com/kovidgoyal/calibre/commits/master/setup/linux-installer.py are not sync'd with Calibre releases!
# - name: FORCE AN UPGRADE IF calibre-installer.py HAS CHANGED, IF SO ORIGINAL IS SAVED TO {{ calibre_download_output.backup_file }}
#   file:
#     path: /usr/bin/calibre-uninstall
#     state: absent
#   when: calibre_download_output.backup_file is defined

- name: Check if calibre-installer.py exists in /opt/iiab/downloads
  stat:
    path: "{{ downloads_dir }}/calibre-installer.py"
  register: calib_inst

# MOVED UP TO roles/calibre/tasks/main.yml (now checks for /usr/bin/calibre)
#- name: Check if calibre-uninstall exists in /usr/bin
#  stat:
#    path: "/usr/bin/calibre-uninstall"
#  register: calib_uninst

- name: FAIL (force Ansible to exit) IF /opt/iiab/downloads/calibre-installer.py OR Internet ARE MISSING
  # meta: end_play
  fail:
    msg: "{{ downloads_dir }}/calibre-installer.py and an Internet connection are REQUIRED in order to install Calibre!"
  when: not calib_inst.stat.exists
  #when: (not calib_inst.stat.exists) or (not internet_available and not calib_uninst.stat.exists)

# INSTALL THE LATEST CALIBRE (calibre, calibredb, calibre-server etc)

- name: Run calibre-installer.py to install Calibre programs into /usr/bin
  shell: "{{ downloads_dir }}/calibre-installer.py >> /dev/null"
  #args:
  #  creates: /usr/bin/calibre-uninstall
