#!/bin/bash
set -eu
app=$YNH_APP_INSTANCE_NAME


# The main logic is to
# - install in a src-new folder
# - upgrade dependencies
# - if everything OK, rename src-new to src

# Installation paths
INSTALL_DIR=/opt/yunohost/ihatemoney
PIP=${INSTALL_DIR}/venv/bin/pip
NEW_REQUIREMENTS=${INSTALL_DIR}/src-new/requirements.txt

# Source YunoHost helpers
. /usr/share/yunohost/helpers

domain=$(ynh_app_setting_get "$app" domain)

# Source local utils
source _common.sh

# Optionaly upgrade arg to typed boolean form

is_public=$(ynh_app_setting_get "$app" is_public)

if [ $is_public = "No" ];
then
    is_public=0
else
    is_public=1
fi

ynh_app_setting_set "$app" is_public "$is_public"

# Upgrade code
fetch_and_extract ${INSTALL_DIR}/src-new/ ihatemoney

fix_permissions ${INSTALL_DIR}/src-new/

# Upgrade dependencies
sudo ${PIP} install -r ${NEW_REQUIREMENTS}

# Everything went ok ? Let's keep this code.
sudo rm -rf ${INSTALL_DIR}/src
sudo mv ${INSTALL_DIR}/src-new ${INSTALL_DIR}/src

# Re-create settings symlink
sudo ln -s /etc/ihatemoney/settings.py ${INSTALL_DIR}/src/budget/settings.py

# Settings are not very likely to change, and that script may be
# adapted to handle it in case.

# Restart backend
sudo supervisorctl restart budget