#!/usr/bin/env bash
#
# Copyright (c) 2024 YunoHost Contributors
#
# This file is part of YunoHost (see https://yunohost.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

readonly GOENV_ROOT="/opt/goenv"
export GOENV_ROOT

_ynh_load_go_in_path_and_other_tweaks() {

    # Get the absolute path of this version of go
    go_dir="$GOENV_ROOT/versions/$go_version/bin"

    if [ ! -e "$go_dir" ]; then
        echo "Skipping loading go, because it doesn't seem to be provisioned yet. This is likely to happen during restore and other specific contexts."
        return
    fi

    # Load the path of this version of go in $PATH
    if [[ :$PATH: != *":$go_dir"* ]]; then
        PATH="$go_dir:$PATH"
    fi

    # Export PATH such that it's available through sudo -E / ynh_exec_as $app
    export PATH

    # This is in full lowercase such that it gets replaced in templates
    path_with_go="$PATH"
    PATH_with_go="$PATH"

    # Sets the local application-specific go version
    pushd "${install_dir}"
        "$GOENV_ROOT/bin/goenv" local "$go_version"
    popd
}

# Auto-load Go path tweaks if this app uses the Go resource in the manifest
if [ -n "${go_version:-}" ] && (cat "$YNH_APP_BASEDIR/manifest.toml" | toml_to_json | jq -e ".resources.go" > /dev/null); then
    _ynh_load_go_in_path_and_other_tweaks
fi

# Install a specific version of Go using goenv
#
# The installed version is defined by `$go_version` which should be defined as global prior to calling this helper
#
# usage: ynh_go_install
#
# The helper adds the appropriate, specific version of go to the `$PATH` variable (which
# is preserved when calling `ynh_exec_as_app`). Also defines:
#
# - `$path_with_go` (the value of the modified `$PATH`, but you dont really need it?)
# - `$go_dir` (the directory containing the specific go version)
ynh_go_install() {

    [[ -n "${go_version:-}" ]] || ynh_die "\$go_version should be defined prior to calling ynh_go_install"

    _ynh_git_clone "https://github.com/syndbg/goenv" "$GOENV_ROOT"
    _ynh_git_clone "https://github.com/momo-lab/xxenv-latest" "$GOENV_ROOT/plugins/xxenv-latest"

    # Enable caching
    mkdir -p "${GOENV_ROOT}/cache"
    # Create shims directory if needed
    mkdir -p "${GOENV_ROOT}/shims"

    # Install the requested version of Go
    local final_go_version=$(PATH=$GOENV_ROOT/bin:$PATH "$GOENV_ROOT/plugins/xxenv-latest/bin/goenv-latest" --print "$go_version")
    go_version=$final_go_version
    ynh_app_setting_set --app="$app" --key="go_version" --value="$go_version"

    ynh_print_info "Installing Go $go_version"
    $GOENV_ROOT/bin/goenv install --quiet --skip-existing "$go_version" 2>&1

    # Cleanup Go versions
    _ynh_go_cleanup

    _ynh_load_go_in_path_and_other_tweaks
}

# Remove the version of Go used by the app.
#
# This helper will also cleanup Go versions
#
# usage: ynh_go_remove
ynh_go_remove() {
    # Remove the line for this app
    ynh_app_setting_delete --key="go_version"

    # Cleanup Go versions
    _ynh_go_cleanup
}

# Remove no more needed versions of Go used by the app.
#
# [internal]
#
# This helper will check what Go version are no more required,
# and uninstall them
# If no app uses Go, goenv will be also removed.
#
# usage: _ynh_go_cleanup
_ynh_go_cleanup() {

    # Remove no more needed Go versions
    local installed_go_versions=$($GOENV_ROOT/bin/goenv versions --bare --skip-aliases | grep -Ev '/')
    for installed_go_version in $installed_go_versions; do
        if ! grep -qE "^go_version: '?$installed_go_version'?" /etc/yunohost/apps/*/settings.yml; then
            # ynh_print_info "Removing Go-$installed_go_version"
            $GOENV_ROOT/bin/goenv uninstall --force "$installed_go_version"
        fi
    done

    # If no app uses Go anymore
    if ! grep -q "^go_version:" /etc/yunohost/apps/*/settings.yml; then
        # Remove goenv environment configuration
        # ynh_print_info "Removing goenv"
        ynh_safe_rm "$GOENV_ROOT"
        ynh_safe_rm "/etc/profile.d/goenv.sh"
    fi
}
