#!/bin/sh -e

##########################################################################
#   Script description:
#       Install miniconda on a FreeBSD system
#       
#   History:
#   Date        Name        Modification
#   2018        Jason Bacon Begin
##########################################################################

usage()
{
    cat << EOM

Usage:      $0 python-version miniconda-version

Visit https://repo.anaconda.com/miniconda/ for a list of available versions.
Note: python-version must include the '.'.

Example:    $0 3.11 25.3.1-1

EOM
    
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ $(whoami) = root ]; then
    cat << EOM

miniconda-installer should not be run as root.  Conda is designed to allow
non-root users to install software packages for their own use.

Many of the community channels contain packages with little or no quality
control or security checks, so running as root is very dangerous.

EOM
    exit 1
fi

if [ $# != 2 ]; then
    usage
fi
python_version=$1
miniconda_version=$2

if [ -e /usr/local/sbin/spcm-node-type ] && \
   [ 0$(/usr/local/sbin/spcm-node-type) != 0compute ]; then
    printf "Error: $0 should only be run on compute nodes.\n"
    exit 1
fi

for dir in proc dev sys; do
    if [ ! -e /compat/linux/$dir ]; then
	cat << EOM

Missing /compat/linux/$dir.  Run "pkg install auto-admin" and
"auto-install-linux_base" as root to complete the Linux compatibility setup.

EOM
	exit 1
    fi
done

# FIXME: Use the mainstream FreeBSD python and download the matching
# script from https://repo.anaconda.com/miniconda/, e.g.
# Miniconda3-py311_25.3.1-1-MacOSX-x86_64.sh
python_version_squashed=$(echo $python_version | tr -d '.')
if [ ! -e /usr/local/bin/python$python_version ]; then
    cat << EOM

This miniconda requires python$python_version.
Install lang/python$python_version_squashed and try again.

EOM
    exit 1
fi

if [ ! -e ~/miniconda3 ]; then
    repo="https://repo.anaconda.com/miniconda"
    # /Miniconda3-py311_25.3.1-1-Linux-x86_64.sh
    script="Miniconda3-py${python_version_squashed}_$miniconda_version-Linux-x86_64.sh"
    if [ ! -e $script ]; then
	fetch $repo/$script
    fi
    /compat/linux/bin/sh $script
    read -p "Remove $script? [y]/n " remove
    if [ 0"$remove" != 0n ]; then
	rm -f $script
    fi

    cat << EOM

To initialize the Linux environment under $(uname), run "conda-shell".

Then run the "eval" command shown above to activate conda.

EOM
    while [ 0"$resp" != 0"got it" ]; do
	read -p 'Type "got it" to confirm. ' resp
    done
else
    printf "miniconda3 already present.  Not reinstalling.\n"
fi
