#!/usr/bin/env bash

nv_cmd_default() {
    local env_name=$(nv_get_first_non_opt_value "$@")
    local save_meta="yes"
    local on_after_install="no"
    local reinstall_env="no"
    local start_new_shell="yes"

    # if env's name is empty try to generate it
    if [ "$env_name" = "" ]; then
    for par in "$@"
    do
    case $par in
        --no-meta)
            ;;
        --force)
            ;;
        --*)
            local plugin_name=$(nv_get_plugin_name $par)
            local plugin_ver=$(nv_get_plugin_version $par)

            env_name="$env_name-$plugin_name-$plugin_ver"
            ;;
    esac
    done
    env_name=`echo "$env_name" | sed "s/^-//"`
    fi

    # check that env name is not empty
    if [ "$env_name" = "" ]; then
        echo "Please, enter a name for a new environment."
        echo ""
        nv_cmd_help
        return 1
    fi

    local env_name_full=$(nv_get_env_full_path $env_name)

    # find --no-meta before installation plugins
    for par in "$@"
    do
    case $par in
        --no-meta)
            save_meta="no"
            ;;
        --force)
            reinstall_env="yes"
    esac
    done

    if [ -d "$env_name_full" ]; then
        if [ "$reinstall_env" = "yes" ]; then
            (nv rm "$env_name")
        else
            echo "Environment with name '$env_name' is already exists."
            echo "Please, choose another name and try again."
            echo ""
            return 1
        fi
    fi

    echo "Creating environment: $env_name ..."
    mkdir -p $env_name_full


    # call each plugin for installation into new env
    for par in "$@"
    do
    case $par in
        # skip this option
        --no-meta)
            ;;
        --force)
            ;;
        --same-shell)
            start_new_shell="no"
            ;;
        --on)
            on_after_install="yes"
            ;;
        # handle plugin only
        --*)
            local plugin_name=$(nv_get_plugin_name $par)
            local plugin_ver=$(nv_get_plugin_version $par)
            local plugin_full_path=$(nv_get_plugin_full_path $plugin_name)

            echo " * installing $plugin_name==$plugin_ver ..."

            # clear main functions
            # http://hyperpolyglot.org/unix-shells
            if [ "`nv_is_function 'plug_list_versions'`" = "yes" ]; then
                unset -f plug_list_versions
            fi
            if [ "`nv_is_function 'plug_url_for_download'`" = "yes" ]; then
                unset -f plug_url_for_download
            fi
            if [ "`nv_is_function 'plug_check_deps'`" = "yes" ]; then
                unset -f plug_check_deps
            fi
            if [ "`nv_is_function 'plug_install'`" = "yes" ]; then
                unset -f plug_install
            fi
            if [ "`nv_is_function 'plug_download'`" = "yes" ]; then
                unset -f plug_download
            fi
            if [ "`nv_is_function 'plug_unpack'`" = "yes" ]; then
                unset -f plug_unpack
            fi
            if [ "`nv_is_function 'plug_configure'`" = "yes" ]; then
                unset -f plug_configure
            fi
            if [ "`nv_is_function 'plug_build'`" = "yes" ]; then
                unset -f plug_build
            fi
            if [ "`nv_is_function 'plug_build_env'`" = "yes" ]; then
                unset -f plug_build_env
            fi
            if [ "`nv_is_function 'plug_post_install_actions'`" = "yes" ]; then
                unset -f plug_post_install_actions
            fi
            unset -v plug_state

            # source plugin code & call installation part
            if [ ! -f "$plugin_full_path" ]; then
                echo " - plugin not exists: $plugin_name"
                continue
            else
                . $plugin_full_path
            fi

            # check if plugin disabled
            if [ "$plug_state" = "disabled" ]; then
                echo " - plugin disabled."
                continue
            fi

            if [ -z "$plugin_ver" ]; then
                echo " - please choose a version (eg. --$plugin_name=\$VERSION, see \`nv ls-versions --$plugin_name\`)."
                continue
            fi

            # check prerequisites for building
            if [ "`nv_is_function 'plug_check_deps'`" = "yes" ]; then
                local check_result=$(plug_check_deps)
                if [ ! "$check_result" = "" ]; then
                    echo '!! ------------------------------------------'
                    echo "!! envirius: Check dependencies failed:"
                    echo "!!"
                    echo "!! $check_result"
                    echo '!! ------------------------------------------'
                    (nv rm "$env_name")
                    return 1;
                fi
            fi

            # save installation start time
            local inst_start_time=$(nv_get_time)

            # main installation part
            if [ "`nv_is_function 'plug_install'`" = "yes" ]; then
                plug_install $plugin_name $plugin_ver $env_name_full || {
                    echo "envirius: unable to fetch source file for $plugin_name==$plugin_ver" >&2
                    return
                }
            else
                plug_install_default $plugin_name $plugin_ver $env_name_full || {
                    echo "envirius: unable to fetch source file for $plugin_name==$plugin_ver" >&2
                    return
                }
            fi

            # if continue failed then removing all
            # created data and exit
            local last_command_res=$?
            if [ "$last_command_res" != "0" ]; then
                echo '!! ------------------------------------------'
                echo '!! envirius: "configure" failed!'
                echo '!! envirius: Please, fix problem & try again!'
                echo '!! ------------------------------------------'
                (nv rm "$env_name")
                return $last_command_res
            fi

            # call post-install actions
            if [ "`nv_is_function 'plug_post_install_actions'`" = "yes" ]; then
                plug_post_install_actions $env_name $env_name_full $plugin_ver
            fi

            # save meta info (if need)
            if [ "$save_meta" = "yes" ]; then
                local info_file_full_path=$(nv_get_env_info_path "$env_name")
                echo "$plugin_name==$plugin_ver" >> "$info_file_full_path"
            fi

            # compute installation time
            local inst_diff_time=$(nv_get_time_diff $inst_start_time)
            echo " * done (in $inst_diff_time secs.)"
    esac
    done

    if [ "$on_after_install" = "yes" ]; then
        if [ "$start_new_shell" = "yes" ]; then
            nv on $env_name
        else
            nv on $env_name --same-shell
        fi
    fi
}

plug_download_default() {
    local plugin_name=$1
    local version=$2

    local tarball_url=$(plug_url_for_download "$version")
    local tarball_filename=$(nv_get_filename "$tarball_url")
    local tarball_ext=$(nv_get_filename_ext "$tarball_filename")
    local tarball_cache="${plugin_name}-${version}.${tarball_ext}"
    local tarball=$(nv_download_file "$tarball_url" "$tarball_cache")

    if [ ! -f "$tarball" ]; then
        echo "envirius: failed to download '$tarball_url'" >&2
        return 1
    fi

    echo "$tarball"
}

# Plugin installation logic.
# Can be overridden in the plugin body
# (for example, in $NV_HOME/nv-plugin/erlang).
#
# Input:
#   $1 — plugin name (erlang, rust, ...)
#   $2 — plugin version
#   $3 — full path to the environment
plug_install_default() {
    local plugin_name=$1
    local version=$2
    local env_name_full=$3

    # execute in subshell
    (
        local src_path=$(nv_get_src_path "$plugin_name" "$version")
        local build_path=$(nv_get_build_path "$plugin_name" "$version")

        # if not buid yet then do it
        if [ ! -d "$build_path" ]; then

            # if not unpacked yet then do it
            if [ ! -d "$src_path" ]; then

                # downloading source file
                if [ "`nv_is_function 'plug_download'`" = "yes" ]; then
                    local tarball=$(plug_download $plugin_name $version)
                else
                    local tarball=$(plug_download_default $plugin_name $version)
                fi

                if [ -z "$tarball" ]; then
                    return 1
                fi

                # unpacking source file
                mkdir -p "$src_path"
                if [ "`nv_is_function 'plug_unpack'`" = "yes" ]; then
                    plug_unpack $tarball $src_path
                else
                    tar -xzf "$tarball" -C "$src_path"
                fi
            fi

            mkdir -p "$build_path"

            if [ "`nv_is_function 'plug_build'`" = "yes" ]; then
                plug_build "$src_path" "$build_path"
            else
                # change directory
                local subdir=$(find "$src_path" -mindepth 1 -maxdepth 1 -type d)
                cd "$subdir"

                # compiling
                if [ "`nv_is_function 'plug_configure'`" = "yes" ]; then
                    plug_configure "$build_path"
                else
                    ./configure --prefix="$build_path" || {
                        rm -rf "$build_path"
                        exit 1;
                    }
                fi
                make --jobs=$(nv_get_cpu_count)
                make install
            fi

            # remove unpacked stuff
            rm -rf "$src_path"
        fi

        # copy all bins into new environment
        if [ "`nv_is_function 'plug_build_env'`" = "yes" ]; then
            plug_build_env "$build_path" "$env_name_full"
        else
            cp -r "$build_path"/* $env_name_full
        fi
    )
}

nv_cmd_desc() {
    echo "Create environment"
}

nv_cmd_help() {
    nv_show_usage "[env-name] [--plugin=version [,--plugin=version]]"
    nv_show_desc "$(nv_cmd_desc)"
    echo ""
    echo "Options:"
    echo "  --on         Activate environment after installation"
    echo "  --same-shell Enable environment in the same shell (only if --on entered)"
    echo "  --no-meta    Do not store meta information in the environment (plugin list)."
    echo "  --force      Re-create environment if it already exists"
    echo ""
    echo "Examples:"
    echo "    If environment name is empty then it will be ganerated automatically."
    echo "    For example:"
    echo "      $ $(nv_cmd_name) mk --rust=0.9 --erlang=17.0-rc1"
    echo "    Will genarate environment with name 'rust-0.9-erlang-17.0-rc1'."
    echo ""
    echo "    To see all available plugins execute:"
    echo "      $ $(nv_cmd_name) ls-plugins"
}

# /* vim: set filetype=sh : */
