#!/bin/bash

#=================================================
# GENERIC START
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

source _common.sh
source /usr/share/yunohost/helpers

#=================================================
# CHECK VERSION
#=================================================

upgrade_type=$(ynh_check_app_version_changed)

#=================================================
# ENSURE DOWNWARD COMPATIBILITY
#=================================================
ynh_script_progression --message="Ensuring downward compatibility..."

# Remove the option backup_core_only if it's in the settings.yml file
ynh_app_setting_delete --app=$app --key=backup_core_only

# If maintenance_mode doesn't exist, create it
if [ -z "${maintenance_mode:-}" ]; then
	maintenance_mode=0
	ynh_app_setting_set --app=$app --key=maintenance_mode --value=$maintenance_mode
fi

# If fpm_footprint doesn't exist, create it
if [ -z "${fpm_footprint:-}" ]; then
	fpm_footprint=high
	ynh_app_setting_set --app=$app --key=fpm_footprint --value=$fpm_footprint
fi

# If fpm_free_footprint doesn't exist, create it
if [ -z "${fpm_free_footprint:-}" ]; then
	fpm_free_footprint=0
	ynh_app_setting_set --app=$app --key=fpm_free_footprint --value=$fpm_free_footprint
fi

# If fpm_usage doesn't exist, create it
if [ -z "${fpm_usage:-}" ]; then
	fpm_usage=medium
	ynh_app_setting_set --app=$app --key=fpm_usage --value=$fpm_usage
fi

# Delete existing ini configuration file (backward compatibility)
if [ -f /etc/php/$YNH_PHP_VERSION/fpm/conf.d/20-$app.ini ]; then
    ynh_secure_remove --file=/etc/php/$YNH_PHP_VERSION/fpm/conf.d/20-$app.ini
fi

#=================================================
# PHP-FPM CONFIGURATION
#=================================================
ynh_script_progression --message="Upgrading PHP-FPM configuration..." --weight=2

# Recreate a dedicated PHP-FPM config
ynh_add_fpm_config --usage=$fpm_usage --footprint=$fpm_footprint

#=================================================
# NGINX CONFIGURATION
#=================================================
ynh_script_progression --message="Upgrading NGINX web server configuration..." --weight=2

ynh_backup_if_checksum_is_different --file="/etc/nginx/conf.d/$domain.d/$app.conf"

# Delete current NGINX configuration to be able to check if .well-known is already served.
ynh_remove_nginx_config
ynh_app_setting_delete --app=$app --key="checksum__etc_nginx_conf.d_$domain.d_$app.conf"

# Wait untils NGINX has fully reloaded
ynh_systemd_action --service_name=nginx --action=reload --line_match="Reloaded" --log_path="systemd"

# Check if .well-known is available for this domain
if is_url_handled --domain="$domain" --path="/.well-known/caldav" || is_url_handled --domain="$domain" --path="/.well-known/carddav"
then
    ynh_print_warn --message="Another app already uses the domain $domain to serve a CalDAV/CardDAV feature. You may encounter issues when dealing with your calendar or address book."

    # Remove lines about .well-known/carddav and caldav with sed.
    sed --in-place --regexp-extended '/location = \/\.well\-known\/(caldav|carddav)/d' "../conf/nginx.conf"
fi

# Create a dedicated NGINX config
ynh_add_nginx_config

#=================================================
# SPECIFIC UPGRADE
#=================================================
# MAKE SEQUENTIAL UPGRADES FROM EACH MAJOR
# VERSION TO THE NEXT ONE
#=================================================

current_version=$(grep OC_VersionString "$install_dir/version.php" | cut -d\' -f2)
current_major_version=${current_version%%.*}

# Define a function to execute commands with `occ`
exec_occ() {
    # Backward compatibility to upgrade from older versions
    if [ $current_major_version = "last" ] || [ $current_major_version -ge 24 ]
    then
        NEXTCLOUD_PHP_VERSION=$phpversion
    elif [ $current_major_version -ge 15 ]
    then
        NEXTCLOUD_PHP_VERSION="7.4"
    else
        NEXTCLOUD_PHP_VERSION="7.0"
    fi
(cd "$install_dir" && ynh_exec_as "$app" \
    php$NEXTCLOUD_PHP_VERSION --define apc.enable_cli=1 occ --no-interaction --no-ansi "$@")
}

#=================================================
# HANDLE DATABASE MIGRATION
#=================================================

mysql_db_pwd=$(ynh_app_setting_get --app=$app --key=mysqlpwd)
if [ -n "$mysql_db_pwd" ]
then
    ynh_script_progression --message="Migrating to PostgreSQL database..."

    ynh_backup_if_checksum_is_different --file="$install_dir/config/config.php"

    ynh_psql_test_if_first_run
    ynh_psql_setup_db --db_user=$db_user --db_name=$db_name

    exec_occ db:convert-type --all-apps --clear-schema pgsql $db_name 127.0.0.1 $db_name --password=$db_pwd -n

    ynh_mysql_remove_db --db_user=$db_user --db_name=$db_name
    ynh_app_setting_delete --app=$app --key=mysqlpwd

    ynh_store_file_checksum --file="${install_dir}/config/config.php"
fi

if [ "$upgrade_type" == "UPGRADE_APP" ]
then
    ynh_script_progression --message="Upgrading Nextcloud..." --weight=3

    # Load the last available version
    source upgrade.d/upgrade.last.sh
    last_version=$next_version

    last_major_version=${last_version%%.*}

    # Set write access for the following commands
    chown -R $app: "$install_dir" "$data_dir"

    # Print the current version number of Nextcloud
    exec_occ -V


    # Upgrade may fail if this app is enabled
    # Take all apps enabled, and check if mail is one of them
    # Then temporary disable the mail app
    mail_app_must_be_reactived=0
    
    if exec_occ app:list | awk '/Enabled/{f=1;next} /Disabled/{f=0} f' | grep -q -w mail; then
        exec_occ app:disable mail
        mail_app_must_be_reactived=1
    fi
    
    # While the current version is not the last version, do an upgrade
    while [ "$last_version" != "$current_version" ]
    do

        # The major version is the first part of the version number
        current_major_version=${current_version%%.*}

        if [ ! -f upgrade.d/upgrade.$current_major_version.sh ]; then
            source upgrade.d/upgrade.last.sh
        else
            source upgrade.d/upgrade.$current_major_version.sh
        fi

        # If the current version has the same major version than the next one,
        # then it's the last upgrade to do
        # We also cover the case where the last version is the first of the current major version series
        # (e.g. 20.0.0 is the latest version)
        if [[ ("$last_major_version" -eq "$current_major_version") || ( ("$last_major_version" -eq "$((current_major_version+1))") && ("$next_version" == "$last_version") ) ]]; then
            current_major_version=last
            # Enable YunoHost patches on Nextcloud sources
            cp -a ../sources/patches_last_version/* ../sources/patches
        fi

        # Load the value for this version
        source upgrade.d/upgrade.$current_major_version.sh

        ynh_print_info --message="Upgrade to Nextcloud $next_version"

        # Create an app.src for this version of Nextcloud
        cat > ../conf/app.src << EOF
SOURCE_URL=https://download.nextcloud.com/server/releases/nextcloud-$next_version.tar.bz2
SOURCE_SUM=$nextcloud_source_sha256
SOURCE_SUM_PRG=sha256sum
SOURCE_FORMAT=tar.bz2
SOURCE_IN_SUBDIR=true
EOF

        # Create a temporary directory
        tmpdir="$(ynh_smart_mktemp min_size=300)"

        # Install the next nextcloud version in $tmpdir
        ynh_setup_source --dest_dir="$tmpdir"

        # Enable maintenance mode
        exec_occ maintenance:mode --on

        # Backup the config file in the temp dir
        cp -a "$install_dir/config/config.php" "$tmpdir/config/config.php"

        # Backup 3rd party applications from the current Nextcloud
        # But do not overwrite if there is any upgrade
        # (apps directory already exists in Nextcloud archive)
        (
        cd $install_dir/apps
        for nc_app_dir in */
        do
          if [ ! -d "$tmpdir/apps/$nc_app_dir" ]
          then
            cp -a "$nc_app_dir" "$tmpdir/apps/$nc_app_dir"
          fi
        done
        )

        # Replace the old Nextcloud by the new one
        ynh_secure_remove --file="$install_dir"
        mv "$tmpdir" "$install_dir"
        ynh_secure_remove --file="$tmpdir"

        # Set write access for the following commands
        chown -R $app: "$install_dir" "$data_dir"

        # Upgrade Nextcloud (SUCCESS = 0, UP_TO_DATE = 3)
        exec_occ maintenance:mode --off
        exec_occ upgrade \
        || [ $? -eq 3 ] || ynh_die --message="Unable to upgrade Nextcloud"

        # Get the new current version number
        current_version=$(grep OC_VersionString "$install_dir/version.php" | cut -d\' -f2)
        current_major_version=${current_version%%.*}

        # Print the current version number of Nextcloud
        exec_occ -V
    done

    exec_occ db:add-missing-indices -n
    exec_occ db:add-missing-columns -n
    exec_occ db:add-missing-primary-keys -n
    exec_occ db:convert-filecache-bigint -n
    
    #=================================================
    # CONFIGURE NEXTCLOUD
    #=================================================
    ynh_script_progression --message="Reconfiguring Nextcloud..." --weight=9

    # Verify the checksum and backup the file if it's different
    ynh_backup_if_checksum_is_different --file="$install_dir/config/config.php"

    nc_conf="${install_dir}/config.json"
    ynh_add_config --template="../conf/config.json" --destination="$nc_conf"

    # Reneable the mail app
    if [ $mail_app_must_be_reactived -eq 1 ]; then
        exec_occ app:enable mail
    fi

    # Ensure that UpdateNotification app is disabled
    exec_occ app:disable updatenotification

    # Enable LDAP plugin
    exec_occ app:enable user_ldap

    # Load the config file in nextcloud
    exec_occ config:import "$nc_conf"

    # Then remove the config file
    ynh_secure_remove --file="$nc_conf"

    #=================================================
    # ALLOW USERS TO DISCONNECT FROM NEXTCLOUD
    #=================================================

    # Add dynamic logout URL to the config
    exec_occ config:system:get logout_url >/dev/null 2>&1 \
    || echo "
    //-YunoHost-
    // set logout_url according to main domain
    \$main_domain = exec('cat /etc/yunohost/current_host');
    \$CONFIG['logout_url'] = 'https://'.\$main_domain.'/yunohost/sso/?action=logout';
    //-YunoHost-
    " >> "$install_dir/config/config.php"

    #=================================================
    # CHANGE HOSTNAME FOR ACTIVITY NOTIFICATIONS
    #=================================================

    exec_occ config:system:set overwrite.cli.url --value="https://${domain}"

    #=================================================
    # MOUNT HOME FOLDERS AS EXTERNAL STORAGE
    #=================================================

    # Enable External Storage and create local mount to home folder as needed
    if [ $user_home -eq 1 ]; then
        exec_occ app:enable files_external
        exec_occ files_external:list --output=json \
        | grep -q '"storage":"\\\\OC\\\\Files\\\\Storage\\\\Local"' \
        || create_external_storage "/home/\$user" "Home"
        # Iterate over users to extend their home folder permissions
        for u in $(ynh_user_list); do
        setfacl --modify g:$app:rwx "/home/$u" || true
        done
    fi

    #=================================================
    # STORE THE CHECKSUM OF THE CONFIG FILE
    #=================================================

    # Calculate and store the config file checksum into the app settings
    ynh_store_file_checksum --file="${install_dir}/config/config.php"
fi

#=================================================
# UPDATE THE CRON JOB
#=================================================

cron_path="/etc/cron.d/$app"
ynh_add_config --template="../conf/nextcloud.cron" --destination="$cron_path"
chown root: "$cron_path"
chmod 644 "$cron_path"

exec_occ background:cron

#=================================================
# GENERIC FINALIZATION
#=================================================
# SECURE FILES AND DIRECTORIES
#=================================================

# Fix app ownerships & permissions
chown -R $app:www-data "$install_dir"
chown -R $app: "$data_dir"
find $install_dir/ -type f -print0 | xargs -r0 chmod 0644
find $install_dir/ -type d -print0 | xargs -r0 chmod 0755
find $data_dir/data/ -type f -print0 | xargs -r0 chmod 0640
find $data_dir/data/ -type d -print0 | xargs -r0 chmod 0750
chmod 640 "$install_dir/config/config.php"
chmod 755 /home/yunohost.app
chmod 750 $install_dir

#=================================================
# WARNING ABOUT THIRD-PARTY APPS
#=================================================

if [ "$upgrade_type" == "UPGRADE_APP" ]
then
    # Warn about possible disabled apps
    ynh_print_warn --message="Note that if you've installed some third-parties Nextcloud applications, \
    they are probably disabled and you'll have to manually enable them again."
fi

#=================================================
# SETUP LOGROTATE
#=================================================
ynh_script_progression --message="Upgrading logrotate configuration..."

# Use logrotate to manage app-specific logfile(s)
ynh_use_logrotate --non-append

#=================================================
# SETUP FAIL2BAN
#=================================================
ynh_script_progression --message="Reconfiguring Fail2Ban..." --weight=7

# Create a dedicated Fail2Ban config
ynh_add_fail2ban_config --logpath="/home/yunohost.app/$app/data/nextcloud.log" --failregex="^.*Login failed: '.*' \(Remote IP: '<HOST>'.*$" --max_retry=5

#=================================================
# GENERIC FINALIZATION
#=================================================
# RELOAD NGINX
#=================================================
ynh_script_progression --message="Reloading PHP-FPM..." --weight=2

ynh_systemd_action --service_name="php${phpversion}-fpm" --action=reload

#=================================================
# END OF SCRIPT
#=================================================

ynh_script_progression --message="Upgrade of $app completed" --last