#!/bin/sh -e

pause()
{
    printf "Press Enter to continue..."
    read junk
}


##########################################################################
#   Script description:
#       Automatically install and configure dreckly.
#
#   History:
#   Date        Name        Modification
#   2014-05-19  Jason Bacon Begin
##########################################################################

usage()
{
    cat << EOM

Usage: $0 [--help] \\
	  [--extract-only] \\
	  [--bootstrap-gcc version] \\
	  [--git absolute-path] \\
	  [boostrap-flags]

The following dreckly bootstrap flags are automatically generated by
auto-dreckly-setup:

    --abi
    --unprivileged
    --prefix
    --pkgdbdir
    --sysconfdir
    --varbase
    --prefer-pkgsrc=yes
    --workdir

Any arguments to auto-dreckly-setup besides --help, --extract-only, or
--bootstrap-gcc are passed directly to the dreckly boostrap script,
after the flags listed above.

EOM
    exit 1
}


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

while echo $1 | grep '^--'; do
    if [ $1 = --extract-only ]; then
	EXTRACT_ONLY=yes
	shift
    elif [ $1 = --bootstrap-gcc ]; then
	GCC_VER=$2
	shift
	shift
    elif [ $1 = --git ]; then
	GIT=$2
	shift
	shift
    else
	usage
    fi
done

if [ $(uname) = SunOS ] && ! which gtar > /dev/null 2>&1; then
    printf "You need gtar on SunOS.  Run pkg install gnu-tar.\n"
    exit 1
fi

# Make sure everything from here on is world-readable
umask=$(umask)
# Make sure format is consistent across platforms
umask=$(printf "%04o" $umask)
if [ $umask != 0022 ]; then
    cat << EOM

********************************** WARNING **********************************

umask should generally be 0022 for dreckly bootstrap and package builds to
ensure that most files are world-readable and certain private files are
protected.  Changing permissions on installed dreckly files later is tricky
since you will have to know about special permissions on all files that
require them.

Your umask is $umask.

EOM
    printf "Use umask $umask? y/[n] "
    read continue
    if [ 0$continue != 0y ]; then
	printf "Using umask 022.\n"
	umask 022
    fi
fi

# AD servers might add funky stuff to IDs
if id -gn | fgrep -q ' ' || id -gn | fgrep -q '\'; then
    cat << EOM

Your primary group ID, "`id -gn`", contains white space or special
characters.

This will cause the dreckly bootstrap to fail.  Please install as
a different user with no special characters in the user or group names.

EOM
    exit 1
fi

start_dir=`pwd`
YUM_JAVA_VERSION=11
YUM_TOOLS="gcc gcc-c++ gcc-gfortran java-$YUM_JAVA_VERSION-openjdk-devel tar curl git ncompress"
APT_TOOLS="gcc g++ gfortran default-jdk-headless tar curl git"

if [ `id -un` = root ]; then
    # RHEL / CentOS base
    if [ -e /etc/redhat-release ]; then
	printf "Installing base development tools via yum...\n"
	yum install -y $YUM_TOOLS
    elif [ -e /etc/debian_version ]; then
	printf "Installing base development tools via apt...\n"
	apt install -y $APT_TOOLS
    elif [ $(uname) = FreeBSD ]; then
	pkg install -y gcc openjdk17 curl git
    fi
fi
if [ $(uname) != NetBSD ]; then
    printf "Checking for required tools...\n"

    if ! which java > /dev/null 2>&1; then
	cat << EOM

Warning: No Java installation detected and the openjdk packages only build
on certain BSD and SunOS systems.  On Linux, Mac OS X, and other platforms,
you should install the JDK of your choice before bootstrapping dreckly.

On Debian-based systems, run the following as root:

	apt install $APT_TOOLS

On RHEL-based systems, run:

	yum install $YUM_TOOLS

EOM
	printf "Continue without Java? y/[n] "
	read continue
	if [ 0$continue != 0y ]; then
	    exit 1
	fi
    fi

    tools="cc c++ tar curl"
    if [ -z "$GIT" ]; then      # Full git path provided by user
	tools="$tools git"
    fi
    for tool in $tools; do
	if ! which $tool > /dev/null 2>&1; then
	    if [ $tool = cc ] && which gcc > /dev/null 2>&1; then
		continue;
	    elif [ $tool = c++ ] && which g++ > /dev/null 2>&1; then
		continue;
	    fi
	    missing="$missing $tool"
	fi
    done
    if [ -n "$missing" ]; then
	cat << EOM

Missing required tools:$missing

Please install these tools via your operating system's native package manager
and run $0 again.

On Linux systems you should also install gfortran along with gcc and g++.

On Debian-based systems:

    apt install -y $APT_TOOLS

On Fedora/RHEL-based systems:

    yum install -y $YUM_TOOLS

On Illumos:

    pkg update
    reboot      # To load new boot env
    pkg install developer/gcc-13 git openjdk18 gnu-tar

EOM
	exit 1
    fi
fi
if [ -z "$GIT" ]; then
    GIT=$(which git)
fi

# Debian dash is not compatible
if [ -e /etc/debian_version ] && [ -e /bin/bash ]; then
    SH=/bin/bash
    export SH
fi

# Special case: auto-dreckly-setup should remain standalone, so use
# uname instead of auto-ostype.  Don't introduce dependencies on any
# other auto-admin scripts.
# For OS X, we should install a new base gcc using install-base-gcc
case $(uname) in
'Darwin')
    if [ ! -e /usr/bin/gcc ]; then
	cat << EOM

You must install Xcode command-line tools in order to use dreckly.

EOM
	exit 1
    fi
    os_major=`uname -r | cut -d . -f 1`

    # On 13.4, bootstrap fails with "C compiler cannot create executables"
    # export MACOSX_DEPLOYMENT_TARGET=`sw_vers --productVersion`

    # Just use the /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk symlink
    # instead of a specific MacOSX.x.y.sdk
    export OSX_TOLERATE_SDK_SKEW=yes
    ;;

CYGWIN*)
    cat << EOM

You MUST have the following Cygwin packages installed:

    devel/gcc
    devel/g++
    devel/gfortran
    devel/make
    lib/mpfr (required by gcc, but not installed automatically)
    net/curl or web/wget

Ideally, no other Cygwin packages should be installed.  Libraries and tools
installed by Cygwin could be found and used by configure scripts in dreckly
packages.  As with all package systems, It is better if all dreckly
dependencies are installed by dreckly.  Dreckly does its best to ensure that
this happens, but configure scripts have minds of their own and dreckly cannot
control them completely.

EOM
    pause
    ;;
esac

if [ -e /opt/local/bin/port ]; then
    cat << EOM

============================================================================
You appear to be using MacPorts.  MacPorts and dreckly can coexist, but you
must ensure that your environment is configured to avoid mixing them.  Your
PATH, LD_LIBRARY_PATH, and any other variables that select components of
MacPorts or dreckly must be configured at all times to use one or the other,
but never both (unless you know what you're doing).
============================================================================
EOM
    pause
fi

if [ -e /sw/bin ]; then
    cat << EOM

============================================================================
You appear to be using Fink.  Fink and dreckly can coexist, but you
must ensure that your environment is configured to avoid mixing them.  Your
PATH, LD_LIBRARY_PATH, and any other variables that select components of
MacPorts or dreckly must be configured at all times to use one or the other,
but never both (unless you know what you're doing).
============================================================================
EOM
    pause
fi

cat << EOM

============================================================================
Default responses are shown in [].  Simple press Enter to accept defaults.

Type Ctrl+c at any time to stop installation.
============================================================================
EOM

if [ `id -un` != 'root' ]; then
    cat << EOM

============================================================================
Not running as root.  Installing as user $(id -un).  This is fine, but
is typically only used to install dreckly for your own exclusive use
on a system for which you don't have administrator rights.  If you want
to install dreckly for multiple users, you may prefer to cancel now and
re-run this script as root.
============================================================================

EOM
    # Not all systems have a realpath command
    mkdir -p $HOME/Dreckly
    default_parent=`(cd "$HOME/Dreckly"; pwd -P)`
else
    cat << EOM
    
============================================================================
Running as root.  Installing globally.
============================================================================

EOM
    if [ $(uname) = Darwin ]; then
	default_parent="/opt"
    elif [ $(uname) = OpenBSD ]; then
	# OpenBSD has a very small /usr partition by default, meant to
	# contain only the base system.
	default_parent="/usr/local"
    else
	default_parent="/usr"
    fi
fi
printf "OK to proceed? [y]/n "
read proceed
if [ "0$proceed" = "0n" ]; then
    exit
fi

printf "Installation parent directory? [$default_parent] "
read parent
if [ 0"$parent" = 0 ]; then
    parent=$default_parent
else
    rmdir $default_parent || true
fi

snapshot=git

dist_suffix="-`date +%Y-%m-%d`"

cat << EOM
=============================================================================
Dreckly supports multiple installations on the same computer.
Auto-dreckly-setup handles multiple installations under the same parent by
appending the date of a current snapshot or the name of a quarterly snapshot.

It is recommended that you use an install suffix unless you are sure that
you will not need another dreckly tree under 

    $parent
    
It also helps identify the version of each tree.
=============================================================================
EOM

printf "Add suffix to installation directories? y/[n] "
read use_dir_suffix
if [ 0$use_dir_suffix = 0y ]; then
    printf "Suffix? [$dist_suffix] "
    read chosen_suffix
    if [ 0$chosen_suffix != 0 ]; then
	dir_suffix="$chosen_suffix"
    else
	dir_suffix="$dist_suffix"
    fi
else
    dir_suffix=''
fi

if [ -n "$GCC_VER" ]; then
    prefix=$parent/pkg-gcc$GCC_VER$dir_suffix
    dreckly_dir=$parent/dreckly-gcc$GCC_VER$dir_suffix
    sys_dir=$parent/pkg-gcc$GCC_VER$dir_suffix
else
    prefix=$parent/pkg$dir_suffix
    dreckly_dir=$parent/dreckly$dir_suffix
    sys_dir=$parent/pkg$dir_suffix
fi
mk_conf=$sys_dir/etc/mk.conf

cat << EOM

============================================================================
Packages will be installed under

    $prefix
    
Frameworks for building and installing will be under

    $dreckly_dir

System files will be under

    $sys_dir
============================================================================

EOM

pause

# Base compiler setup
cat << EOM

============================================================================
You will need at least a C compiler and a C++ compiler to build most
dreckly packages.  Many packages also require a Fortran compiler.  On
many systems, such as NetBSD, dreckly can build its own Fortran compilers.
On RHEL/CentOS, using the gfortran compiler provided via Yum works well.

If dreckly is bootstrapped to use the GCC compiler collection,
it will look for gfortran in the PATH when building certain packages.
============================================================================
EOM

# Avoid software from other package managers or cave-man installs
# This may need alteration on some platforms, but it works on RHEL,
# FreeBSD, NetBSD, and OS X.
PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/pkg/bin
if [ -n "$COMPILER_PATH" ]; then
    PATH=${COMPILER_PATH}:$PATH
fi
export PATH

# Scrub the environment to avoid self-inflicted problems.
# Users commonly add things to their login scripts to "fix" a particular
# build, not realizing that the same things break other builds.
# Use dreckly-non-exclusive.sh instead if you really want the env left alone.
# Some standard variables, not all of which are scrubbed here:
# https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html
# https://gcc.gnu.org/onlinedocs/cpp/Environment-Variables.html
unset CC CFLAGS CXX CXXFLAGS CPP CPPFLAGS CPATH \
    C_INCLUDE_PATH CPLUS_INCLUDE_PATH OBJC_INCLUDE_PATH \
    FC FFLAGS GFLAGS LD LDFLAGS LD_LIBRARY_PATH LDLIBS

printf "Compilers in your current PATH include:\n\n"
if ! which cc > /dev/null 2>&1; then
    if ! which gcc > /dev/null 2>&1; then
	printf "No C compiler found.  Aborting...\n"
	exit 1
    fi
fi
if ! which c++ > /dev/null 2>&1; then
    if ! which g++ > /dev/null 2>&1; then
	printf "No C++ compiler found.  Aborting...\n"
	exit 1
    fi
fi

printf "\nThese same compilers must be first in PATH when building packages.\n"
printf "\nProceed? [y]/n "
read proceed
if [ 0$proceed = 0n ]; then
    exit 0
fi

if ! which gfortran > /dev/null 2>&1; then
    # Dreckly GCC packages don't currently build on FreeBSD.
    # It's better to use the ports gfortran anyway, since it's easier
    # to install and tested for compatibility with FreeBSD clang.
    if [ $(uname) = FreeBSD ]; then
	cat << EOM

No gfortran found.  On FreeBSD, you must install gfortran via
FreeBSD ports before running $0.  The FreeBSD ports
gfortran is much easier to install than the dreckly packages,
and is tested for compatibility with FreeBSD clang.

Run 'pkg install gcc' as root, then run $0 again.

EOM
	exit 1
    fi
    cat << EOM

============================================================================
No Fortran compiler was found in your PATH.

On Debian compatible systems, run:

    apt install gfortran

On RHEL compatible systems, run:

    yum install gcc-gfortran

before bootstrapping dreckly.

Otherwise, dreckly will attempt to install a Fortran compiler when needed.
============================================================================

EOM
    printf "Continue without Fortran in the base compiler suite? [y]/n "
    read resp
    if [ 0$resp = 0n ]; then
	exit 1
    fi
    # Use gfortran rather than g95.
    # FIXME: This may be default on all platforms now
    use_gfortran=y
fi

if [ -z "$GCC_VER" ] && [ $(uname -p) != powerpc ]; then
    cat << EOM

============================================================================
Compiling with -march=native can result in executables that run up to 30%
faster in some cases, though usually less.  The binary packages created
will not be portable, however, and will only run on CPUs with all the
same features as this one.

If you are using this system to generate binary packages for use on other
systems, answer 'n' here.

If you want executables optimized for maximum speed on this system, answer
'y'.  This will append -march=native to CFLAGS, CXXFLAGS, and FFLAGS in

    $sys_dir/etc/mk.conf

You can add additional compiler flags here as well, all of which will be
applied to every dreckly build.

EOM
    printf "Build all compiled packages with -march=native? y/[n] "
    read march_native
else
    march_native=n
fi

if which /usr/bin/fetch > /dev/null 2>&1; then   # FreeBSD
    fetch_cmd=fetch
elif [ -e /usr/pkg/bin/fetch ]; then        # NetBSD
    fetch_cmd=/usr/pkg/bin/fetch
elif which curl > /dev/null 2>&1; then
    fetch_cmd='curl -O'
elif which wget > /dev/null 2>&1; then
    fetch_cmd=wget
elif which ftp > /dev/null 2>&1; then
    fetch_cmd=ftp
else
    printf "No fetch command found.\n"
    exit 1
fi

if [ $snapshot = custom ]; then
    replace_frameworks='n'
elif [ -e $dreckly_dir ]; then
    printf "$dreckly_dir already exists.  Replace? y/[n] "
    read replace_frameworks
else
    replace_frameworks='y'
fi

if [ 0$replace_frameworks = 0y ]; then
    # Download new dreckly dist if a new install number was provided
    if [ $snapshot = git ]; then
	save_cwd=`pwd`
	mkdir -p $parent
	cd $parent
	rm -rf $dreckly_dir $prefix $sys_dir
	default_url='https://github.com/drecklypkg/dreckly.git'
	printf "git URL of dreckly tree? [$default_url] "
	read git_url
	if [ -z "$git_url" ]; then
	    git_url=$default_url
	fi
	$GIT clone $git_url $dreckly_dir
	cd $save_cwd
    elif [ $snapshot = custom ]; then
	download='n'
	cat << EOM

===========================================================================
Place your custom source tree in $dreckly_dir now.
===========================================================================

EOM
	pause
    elif [ -e $parent/Dist/dreckly$dist_suffix.tar.gz ]; then
	printf "dreckly$dist_suffix.tar.gz already exists.  Replace? y/[n] "
	read download
    else
	download='y'
    fi
    
    if [ 0$download = 0y ]; then
	printf "Downloading dist...\n\n"
	# Replace everything after new download
	mkdir -p $parent/Dist
	cd $parent/Dist
	rm -f dreckly.tar.gz
    
	fetched=no
	for dist in \
	    https://ftp.netbsd.org/pub/dreckly/$snapshot/dreckly.tar.gz; do
	    
	    echo $dist
	    if $fetch_cmd $dist; then
		fetched=yes
		break
	    fi
	done
	if [ $fetched = no ]; then
	    printf "Unable to fetch $snapshot from any mirror.  Giving up...\n"
	    exit 1
	fi
	# Make sure dist is in the form dreckly-yearQquarter.tar.gz
	if echo $dist | fgrep ftp.netbsd.org; then
	    mv dreckly.tar.gz dreckly$dist_suffix.tar.gz
	fi
    fi
fi

# Create a new package tree for this installation
if [ $(uname) = SunOS ]; then
    tar=gtar
else
    tar=tar
fi

if [ 0$replace_frameworks = 0y ] && [ $snapshot != git ]; then
    # Replace everything if unpacking again
    rm -rf $dreckly_dir $prefix $sys_dir
    cd $parent/Dist
    printf "Unpacking frameworks...\n"
    # Use of -o and --no-same-permissions is a security requirement.  It
    # prevents root from installing a tree owned by an ordinary user.
    if [ $(uname) = NetBSD ] || [ $(uname) = OpenBSD ]; then
	$tar -zxf dreckly$dist_suffix.tar.gz
    else
	$tar --no-same-permissions -zoxf dreckly$dist_suffix.tar.gz
    fi
    rm -rf $dreckly_dir $sys_dir $prefix
    mv dreckly $dreckly_dir
    if [ 0$EXTRACT_ONLY != 0 ]; then
	exit 0
    fi
fi

if [ -e $prefix/bin/bmake ]; then
    printf "$prefix already exists.  Rebuild? y/[n] "
    read bootstrap
else
    bootstrap='y'
fi

# Snow Leopard uname reports i386, even on 64-bit Core 2 Duo machines,
# so check the hardware and force 64-bit ABI if needed
# Idea:
#    gcc -v |& grep Target
#        i386: --abi 32
#        x86_64: --abi 64

if [ $(uname) = 'Darwin' ] && \
	sysctl -n machdep.cpu.brand_string | grep 'Core(TM)2' ; then
    abi_flags='--abi 64'
else
    abi_flags=''
fi

# Bootstrap the installation
if [ 0$bootstrap = '0y' ]; then
    # Keep old frameworks, but rebuild installation dir and system files
    rm -rf $sys_dir $prefix
    cd $dreckly_dir/bootstrap
    
    # Scrub env to prevent leakage of nonstandard tools into dreckly
    unset CC CFLAGS CXX CXXFLAGS CPP CPPFLAGS CPATH \
	C_INCLUDE_PATH CPLUS_INCLUDE_PATH OBJC_INCLUDE_PATH \
	FC FFLAGS GFLAGS LD LDFLAGS LD_LIBRARY_PATH LDLIBS
    if which cc > /dev/null 2>&1; then
	CC=cc
	CXX=c++
    else
	# Verified presence of gcc above
	CC=gcc
	CXX=g++
    fi
    # OS X 10.12.6 needs full path for bmake build
    CPP=`which cpp`
    # PKGSRC_USE_FORTIFY causes some breakage, including cwrappers on RHEL
    # Enable it in the future if/when most of the issues are resolved
    # PKGSRC_USE_FORTIFY=no
    # Leave fortify on and just disable -Werror.  Sufficient for cwrappers.
    # NOGCCERROR=yes
    # export CC CXX CPP NOGCCERROR # PKGSRC_USE_FORTIFY
    export CC CXX CPP
    
    # Problems with gcc8 generating code with infinite loops on RHEL
    if [ $(uname) = Linux ]; then
	export PKGSRC_USE_FORTIFY=no
    fi
    if [ $(uname) != NetBSD ]; then
	prefer_pkgsrc='--prefer-pkgsrc=yes'
    else
	prefer_pkgsrc=''
    fi

    if [ `id -un` = root ]; then
	./bootstrap \
	    $abi_flags \
	    --prefix ${prefix} \
	    --pkgdbdir ${sys_dir}/pkgdb \
	    --sysconfdir ${sys_dir}/etc \
	    --varbase ${sys_dir}/var \
	    $prefer_pkgsrc \
	    --workdir ${sys_dir}/work 2>&1 \
	    "$@" \
	    | tee bootstrap$dist_suffix.log
    else
	./bootstrap \
	    $abi_flags \
	    --unprivileged \
	    --prefix ${prefix} \
	    --pkgdbdir ${sys_dir}/pkgdb \
	    --sysconfdir ${sys_dir}/etc \
	    --varbase ${sys_dir}/var \
	    $prefer_pkgsrc \
	    --workdir ${sys_dir}/work 2>&1 \
	    "$@" \
	    | tee bootstrap$dist_suffix.log
    fi

    # Separate bootstrap settings
    printf "\n.ifdef BSD_PKG_MK       # Begin auto-dreckly-setup customizations\n\n" >> $mk_conf

    if [ -n "$COMPILER_PATH" ]; then
	for CC in cc gcc; do
	    if [ -e $COMPILER_PATH/$CC ]; then
		printf "CC?=\t\t\t$COMPILER_PATH/$CC\n" >> $mk_conf
		break
	    fi
	done
	for CXX in c++ g++; do
	    if [ -e $COMPILER_PATH/$CXX ]; then
		printf "CXX?=\t\t\t$COMPILER_PATH/$CXX\n" >> $mk_conf
		break
	    fi
	done
	for FC in gfortran; do
	    if [ -e $COMPILER_PATH/$FC ]; then
		printf "FC?=\t\t\t$COMPILER_PATH/$FC\n" >> $mk_conf
		break
	    fi
	done
    fi
    if [ -n "$OSX_TOLERATE_SDK_SKEW" ]; then
	printf "OSX_TOLERATE_SDK_SKEW=\tyes\n" >> $mk_conf
    fi

    #if [ -n "$MACOSX_DEPLOYMENT_TARGET" ]; then
    #    printf "MACOSX_DEPLOYMENT_TARGET=\t\t$\MACOSX_DEPLOYMENT_TARGET\n" >> $mk_conf
    #fi

    printf "# For pkg_chk, etc.\n" >> $mk_conf
    printf "DRECKLYDIR=\t\t$dreckly_dir\n" >> $mk_conf
    
    # PKGSRC_USE_FORTIFY causes some breakage, including cwrappers on RHEL
    # Enable it in the future if/when most of the issues are resolved
    # printf "PKGSRC_USE_FORTIFY=\tno\n" >> $mk_conf
    # Leave fortify on and just disable -Werror
    # gcc49,5,6 fail on RHEL 7 with just this
    # gcc49,5 on RHEL 6
    # printf "NOGCCERROR=\t\tyes\n" >> $mk_conf

    ######################################
    # Configure dreckly options in mk.conf
    ######################################
    
    # Add X11_TYPE=modular tells dreckly to use its own X11 packages
    # Let NetBSD use its own default since Xorg is a big build on
    # some platforms
    if [ $(uname) != NetBSD ] && ! fgrep -q X11_TYPE $mk_conf; then
	printf "X11_TYPE=\t\tmodular\n" >> $mk_conf
    fi
    
    # Testing: Fortify may be causing problems with gcc8 on RHEL 7
    if [ $(uname) = Linux ]; then
	printf "PKGSRC_USE_FORTIFY=\tno\n" >> $mk_conf
    fi

    # GCC packages will fail on Linux with RELRO set
    if [ $(uname) != Linux ]; then
	printf "PKGSRC_USE_RELRO=\tyes\n" >> $mk_conf
    fi

    # FIXME: SSP is known not to work on OpenIndiana, possible others
    if [ $(uname) = SunOS ]; then
	printf "PKGSRC_USE_SSP=\tno\n" >> $mk_conf
    fi
    
    if [ 0$use_gfortran != 0n ]; then
	printf "PKGSRC_FORTRAN=\t\tgfortran\n" >> $mk_conf
    fi
    
    if [ -n "$GCC_VER" ]; then
	developer=n
    else
	printf "Will you be using this installation for package development? y/[n] "
	read developer
	if [ 0$developer = 0y ]; then
	    # FIXME: Override old setting if necessary
	    if ! fgrep PKG_DEVELOPER $mk_conf; then
		printf "PKG_DEVELOPER=\t\tyes\n" >> $mk_conf
	    fi
	fi

	printf "Disable use of RUST to avoid long build times? y/[n] "
	read disable_rust
	if [ 0$disable_rust = 0y ]; then
	    # FIXME: Override old setting if necessary
	    if ! fgrep PLATFORM_SUPPORTS_RUST $mk_conf; then
		printf "PLATFORM_SUPPORTS_RUST=\t\tno\n" >> $mk_conf
	    fi
	fi
    fi
    
    # Github and some other sites are inaccessible via ftp on Linux
    # Try to use a native tool rather than one that dreckly has to install
    # as a dependency
    case $(uname) in
    FreeBSD)
	printf "FETCH_USING=\t\tfetch\n" >> $mk_conf
	;;
    Linux)
	printf "FETCH_USING=\t\tcurl\n" >> $mk_conf
	if ! which curl > /dev/null 2>&1; then
	    cat << EOM

You must install curl via your native Linux package manager, e.g.

	yum install curl
	apt install curl

EOM
	    pause
	fi
	;;
    NetBSD)
	printf "FETCH_USING=\t\tftp\n" >> $mk_conf
	;;
    *)
	;;
    esac
    
    cat << EOM

============================================================================
You can configure dreckly to install any package regardless of the license
type.  Do this only if you are certain that your organization has no
restrictions on the allowable types of licenses.

EOM
    if [ -z "$GCC_VER" ]; then
	printf "Accept all software licenses? [y]/n "
	read skip_license_check
    else
	skip_license_check=y
    fi
    
    if [ 0$skip_license_check != 0n ]; then
	printf "SKIP_LICENSE_CHECK=\tyes\n" >> $mk_conf
    else
	tmpfile=auto-dreckly-setup-license-list
	awk '{
	if ( $1 == "DEFAULT_ACCEPTABLE_LICENSES=" )
	    while ( $NF == "\\" )
	    {
		getline;
		for (c=1; c<NF; ++c) printf("%s ", $c);
	    }
	}' $dreckly_dir/mk/license.mk > $tmpfile
	licenses=`cat $tmpfile`
	rm -f $tmpfile
    
	for license in $licenses; do
	    printf "Allow packages with license $license? [y]/n "
	    read accepted
	    if [ 0$accepted != '0n' ]; then
		printf "ACCEPTABLE_LICENSES+=\t$license\n" >> $mk_conf
	    fi
	done
    fi
    
    # Needed for libfetch and pkgin
    printf "PKG_OPTIONS.libfetch=\tinet6 openssl\n" >> $mk_conf
    
    if [ 0$march_native = 0y ]; then
	printf "CFLAGS+=\t\t-march=native\n" >> $mk_conf
	printf "CXXFLAGS+=\t\t-march=native\n" >> $mk_conf
	printf "FFLAGS+=\t\t-march=native\n" >> $mk_conf
    fi
    
    case $(uname) in
    Linux)
	make_jobs=$(grep '^processor' /proc/cpuinfo|wc -l)
	;;
    Darwin|FreeBSD|OpenBSD|NetBSD)
	make_jobs=$(sysctl -n hw.ncpu)
	;;
    *)
	cat << EOM

Not sure how to determine the number of cores under $(uname).
Set MAKE_JOBS manually in mk.conf if desired and send us a patch if
you know how to fix this.

EOM
	make_jobs=1
	;;
    esac
    printf "MAKE_JOBS=\t\t$make_jobs\n" >> $mk_conf
    printf "\n.endif                  # End auto-dreckly-setup customizations\n" >> $mk_conf

fi  # bootstrap

if [ $(uname) = Linux ] || [ $(uname) = NetBSD ]; then
    major=999
    cat << EOM
=========================================================================

Some packages may require a newer compiler than the native GCC
for this operating system, especially if you are using an older
operating system or an enterprise Linux system, which uses older
tools and libraries for better stability and backward-compatibility
with commercial software.

If you would like to use a dreckly GCC compiler to build most packages
(everything except GCC and its dependencies), enter the major version
number below.  The major version is the number following "gcc" in the
list of packages below.

Determining the best compiler for your needs is a matter of trial and
error, though in general, the 2nd newest compiler is usually a good bet.

Available gcc packages:

EOM
    (cd $dreckly_dir && ls -d lang/gcc[0-9] lang/gcc[0-9][0-9])
    printf "\nCurrent GCC version:\n\n"
    gcc --version | head -n 1
    while [ ! -e $dreckly_dir/lang/gcc$major ]; do
	printf "\nGCC major version? [just press enter for none] "
	read major
	if [ -z "$major" ]; then
	    base_gcc=""
	    break
	elif [ -e $dreckly_dir/lang/gcc$major ]; then
	    base_gcc=gcc$major
	    gcc_version=$major.0
	else
	    printf "$dreckly_dir/lang/gcc$major: No such package.\n"
	fi
    done
    
    # Keep this in sync with pbulk-setup for installations that use both
    # binary packages and build from source.
    if [ -n "$base_gcc" ]; then
	cat << EOM >> $mk_conf

.ifdef BSD_PKG_MK   # dreckly
.if \\
    empty(PKGPATH:Marchivers/bsdtar) && \\
    empty(PKGPATH:Marchivers/bzip2) && \\
    empty(PKGPATH:Marchivers/pax) && \\
    empty(PKGPATH:Marchivers/xz) && \\
    empty(PKGPATH:Mconverters/help2man) && \\
    empty(PKGPATH:Mconverters/libiconv) && \\
    empty(PKGPATH:Mconverters/p5-Unicode-EastAsianWidth) && \\
    empty(PKGPATH:Mdatabases/db4) && \\
    empty(PKGPATH:Mdevel/autoconf) && \\
    empty(PKGPATH:Mdevel/binutils) && \\
    empty(PKGPATH:Mdevel/bison) && \\
    empty(PKGPATH:Mdevel/flex) && \\
    empty(PKGPATH:Mdevel/gettext-lib) && \\
    empty(PKGPATH:Mdevel/gettext-tools) && \\
    empty(PKGPATH:Mdevel/gmake) && \\
    empty(PKGPATH:Mdevel/gmp) && \\
    empty(PKGPATH:Mdevel/gtexinfo) && \\
    empty(PKGPATH:Mdevel/libffi) && \\
    empty(PKGPATH:Mdevel/libtool-base) && \\
    empty(PKGPATH:Mdevel/libuuid) && \\
    empty(PKGPATH:Mdevel/makedepend) && \\
    empty(PKGPATH:Mdevel/pkgconf) && \\
    empty(PKGPATH:Mdevel/m4) && \\
    empty(PKGPATH:Mdevel/ncurses) && \\
    empty(PKGPATH:Mdevel/nbpatch) && \\
    empty(PKGPATH:Mdevel/p5-CPAN-Meta) && \\
    empty(PKGPATH:Mdevel/p5-Module-Build) && \\
    empty(PKGPATH:Mdevel/p5-Perl4-CoreLibs) && \\
    empty(PKGPATH:Mdevel/p5-Scalar-List-Utils) && \\
    empty(PKGPATH:Mdevel/p5-gettext) && \\
    empty(PKGPATH:Mdevel/p5-inc-latest) && \\
    empty(PKGPATH:Mdevel/readline) && \\
    empty(PKGPATH:Mdevel/zlib) && \\
    empty(PKGPATH:Mlang/gcc*) && \\
    empty(PKGPATH:Mlang/perl5) && \\
    empty(PKGPATH:Mlang/python*) && \\
    empty(PKGPATH:Mmath/cloog) && \\
    empty(PKGPATH:Mmath/isl) && \\
    empty(PKGPATH:Mmath/mpcomplex) && \\
    empty(PKGPATH:Mmath/mpfr) && \\
    empty(PKGPATH:Mmisc/p5-Locale-libintl) && \\
    empty(PKGPATH:Mnet/libfetch) && \\
    empty(PKGPATH:Mpkgtools/cwrappers) && \\
    empty(PKGPATH:Mpkgtools/digest) && \\
    empty(PKGPATH:Mpkgtools/mktools) && \\
    empty(PKGPATH:Mpkgtools/pkg_install) && \\
    empty(PKGPATH:Mpkgtools/pkg_install-info) && \\
    empty(PKGPATH:Mpkgtools/pkgin) && \\
    empty(PKGPATH:Msecurity/mozilla-rootcerts*) && \\
    empty(PKGPATH:Msecurity/openssl) && \\
    empty(PKGPATH:Msysutils/checkperms) && \\
    empty(PKGPATH:Mtextproc/gsed) && \\
    empty(PKGPATH:Mtextproc/p5-Text-Unidecode) && \\
    empty(PKGPATH:Mx11/xorgproto) && \\
    empty(PKGPATH:Mpkgtools/libnbcompat)
    
GCC_REQD+=$gcc_version
GFORTRAN_VERSION=$gcc_version

.endif  # GCC_REQD

# Keep this in sync with pbulk-setup
.if (exists(/etc/redhat-release) || exists(/etc/amazon)) && !empty(PKGPATH:Mlang/gcc*)

# FIXME: binutils is broken and might not be necessary anymore anyway.
# This was added for CentOS 6.
#
# RHEL systems may have an outdated "as" that cannot translate instructions
# from current GCC code generators, so force dreckly binutils.
# CONFIGURE_ARGS+=        --with-gnu-as --with-as=\${PREFIX}/bin/gas
# CONFIGURE_ARGS+=        --with-gnu-ld --with-ld=\${PREFIX}/bin/gld
# BUILDLINK_DEPMETHOD.binutils=   full
# .  include "../../devel/binutils/buildlink3.mk"

# dreckly gcc packages don't install libgcc_s on some platforms, to
# avoid problems when mixing compiler versions.  This breaks our use
# of dreckly gcc on EL.
PKG_DEFAULT_OPTIONS+=   always-libgcc
.endif  # RHEL
.endif  # BSD_PKG_MK
EOM
	compiler=gcc-$gcc_version
    else    # Use base compiler
	compiler=cc
    fi
else
    compiler=cc
fi

# Install latest security checks
${prefix}/sbin/pkg_admin \
    -K ${sys_dir}/pkgdb fetch-pkg-vulnerabilities

##########################################################################
#   Some improvements to the base installation
##########################################################################

# Scrub PATH and LD_LIBRARY_PATH to prevent leakage.
# If someone wants to shoot themselves in the foot by adding additional
# non-standard directories, they'll have to load their own bullets and
# unlatch the safety themselves.

# Generate startup script segments

# Prepend COMPILER_PATH to user's PATH if not empty
if [ -n "$COMPILER_PATH" ]; then
    COMPILER_PATH_COLON="${COMPILER_PATH}:"
fi

cat << EOM > ${sys_dir}/etc/dreckly.sh
# Generated by auto-dreckly-setup
# Set env for this dreckly tree if not already set
if ! echo \$PATH | fgrep -q "${prefix}/bin:"; then
    DRECKLY=$prefix
    export DRECKLY
    
    # Scrub PATH and LD_LIBRARY_PATH before adding dreckly to prevent leakage
    # RHEL 7 /bin/gcc fails with cannot find cc1, so put /usr/bin first
    PATH=$PATH
    unset CC CFLAGS CXX CXXFLAGS CPP CPPFLAGS CPATH \
	C_INCLUDE_PATH CPLUS_INCLUDE_PATH OBJC_INCLUDE_PATH \
	FC FFLAGS GFLAGS LD LDFLAGS LD_LIBRARY_PATH LDLIBS
    
    if [ \$(uname) = 'NetBSD' ] || [ \$(uname) = 'SunOS' ]; then
	alias man="man -m \$DRECKLY/man:\$DRECKLY/share/man"
    else
	if which manpath > /dev/null 2>&1; then
	    MANPATH=\$DRECKLY/man:\$DRECKLY/share/man:\$(manpath)
	    export MANPATH
	fi
    fi
    
    PATH=\$DRECKLY/bin:\$DRECKLY/sbin:\$PATH
    export PATH
    DRECKLY_INCLUDE=\$DRECKLY/include
    export DRECKLY_INCLUDE
    DRECKLY_LIB=\$DRECKLY/lib
    export DRECKLY_LIB
fi
EOM

# Keep this in sync with the script above.  Just remove the scrub lines.
cat << EOM > ${sys_dir}/etc/dreckly-non-exclusive.sh
# Generated by auto-dreckly-setup
# Set env for this dreckly tree if not already set
if ! echo \$PATH | fgrep -q "${prefix}/bin:"; then
    DRECKLY=$prefix
    export DRECKLY

    if [ \$(uname) = 'NetBSD' ] || [ \$(uname) = 'SunOS' ]; then
	alias man="man -m \$DRECKLY/man:\$DRECKLY/share/man"
    else
	if which manpath > /dev/null 2>&1; then
	    MANPATH=\$DRECKLY/man:\$DRECKLY/share/man:\$(manpath)
	    export MANPATH
	fi
    fi
    
    PATH=${COMPILER_PATH_COLON}\$DRECKLY/bin:\$DRECKLY/sbin:\$PATH
    export PATH
    DRECKLY_INCLUDE=\$DRECKLY/include
    export DRECKLY_INCLUDE
    DRECKLY_LIB=\$DRECKLY/lib
    export DRECKLY_LIB
fi
EOM

cat << EOM > ${sys_dir}/etc/dreckly.csh
# Generated by auto-dreckly-setup
# Set env for this dreckly tree if not already set
echo \$PATH | fgrep -q "${prefix}/bin:"
if ( \$status != 0 ) then
    setenv DRECKLY           $prefix
    
    # Scrub PATH and LD_LIBRARY_PATH before adding dreckly to prevent leakage
    # RHEL 7 /bin/gcc fails with cannot find cc1, so put /usr/bin first
    setenv PATH $PATH
    unsetenv CC CFLAGS CXX CXXFLAGS CPP CPPFLAGS CPATH \
	C_INCLUDE_PATH CPLUS_INCLUDE_PATH OBJC_INCLUDE_PATH \
	FC FFLAGS GFLAGS LD LDFLAGS LD_LIBRARY_PATH LDLIBS

    if ( \`uname\` == 'NetBSD' || \`uname\` == 'SunOS' ) then
	alias man "man -m \$DRECKLY/man:\$DRECKLY/share/man"
    else
	which manpath >& /dev/null
	if ( \$status == 0 ) then
	    setenv MANPATH \$DRECKLY/man:\$DRECKLY/share/man:\`manpath\`
	endif
    endif
    
    setenv PATH             \$DRECKLY/bin:\$DRECKLY/sbin:\$PATH
    setenv DRECKLY_INCLUDE   \$DRECKLY/include
    setenv DRECKLY_LIB       \$DRECKLY/lib
endif
EOM

# Keep this in sync with the script above.  Just remove the scrub lines.
cat << EOM > ${sys_dir}/etc/dreckly-non-exclusive.csh
# Generated by auto-dreckly-setup
# Set env for this dreckly tree if not already set
echo \$PATH | fgrep -q "${prefix}/bin:"
if ( \$status != 0 ) then
    setenv DRECKLY           $prefix

    if ( \`uname\` == 'NetBSD' || \`uname\` == 'SunOS' ) then
	alias man "man -m \$DRECKLY/man:\$DRECKLY/share/man"
    else
	which manpath >& /dev/null
	if ( \$status == 0 ) then
	    setenv MANPATH \$DRECKLY/man:\$DRECKLY/share/man:\`manpath\`
	endif
    endif
    
    setenv PATH              ${COMPILER_PATH_COLON}\$DRECKLY/bin:\$DRECKLY/sbin:\$PATH
    setenv DRECKLY_INCLUDE   \$DRECKLY/include
    setenv DRECKLY_LIB       \$DRECKLY/lib
endif
EOM

if [ -e /etc/profile.d ]; then
    printf "Add this dreckly installation to default path for all users? y/[n] "
    read add2path
    if [ 0$add2path = 0y ]; then
	cp ${sys_dir}/etc/dreckly.*sh /etc/profile.d
    fi
fi

# Generate module files
mkdir -p ${sys_dir}/etc/modulefiles/dreckly

cat << EOM > ${sys_dir}/etc/modulefiles/dreckly/${dist_suffix#-}
#%Module1.0#####################################################################
proc ModulesHelp { } {
    puts stdout "\n\tAll software installed via the dreckly package management"
    puts stdout "\tsystem. This module prepends the dreckly directories to"
    puts stdout "\tappropriate environment variable(s)."
}

module-whatis   "All software installed via dreckly"

set     version ${dist_suffix#-}
set     prefix  ${prefix}

# Scrub PATH before adding dreckly to prevent leakage during builds
setenv  PATH    /usr/bin:/usr/sbin:/bin:/sbin
unsetenv        CC
unsetenv        CFLAGS
unsetenv        CXX
unsetenv        CXXFLAGS
unsetenv        CPP
unsetenv        CPPFLAGS
unsetenv        FC
unsetenv        FFLAGS
unsetenv        LD
unsetenv        LDFLAGS
unsetenv        LD_LIBRARY_PATH
unsetenv        CPATH
unsetenv        C_INCLUDE_PATH
unsetenv        CPLUS_INCLUDE_PATH
unsetenv        OBJC_INCLUDE_PATH
unsetenv        GFLAGS
unsetenv        LDLIBS

prepend-path    PATH    \$prefix/bin:\$prefix/sbin
# FIXME: Prepend dreckly to existing man path
prepend-path    MANPATH         \$prefix/man:/usr/share/man
prepend-path    MODULEPATH      \$sys_dir/etc/modulefiles

setenv          DRECKLY          \$prefix
setenv          DRECKLY_INCLUDE  \$prefix/include
setenv          DRECKLY_LIB      \$prefix/lib
EOM

# Keep this in sync with the script.  Just remove the scrub lines.
cat << EOM > ${sys_dir}/etc/modulefiles/dreckly/${dist_suffix#-}-non-exclusive
#%Module1.0#####################################################################
proc ModulesHelp { } {
    puts stdout "\n\tAll software installed via the dreckly package management"
    puts stdout "\tsystem. This module prepends the dreckly directories to"
    puts stdout "\tappropriate environment variable(s)."
}

module-whatis   "All software installed via dreckly"

puts stderr "\n======================================================================"
puts stderr "WARNING:\n"
puts stderr "dreckly/${dist_suffix#-}-non-exclusive allows programs and libraries"
puts stderr "that are not part of this dreckly tree or the base system to remain in"
puts stderr "PATH and LD_LIBRARY_PATH.  This may cause some programs to malfunction."
puts stderr "======================================================================\n"

set     version ${dist_suffix#-}
set     prefix  ${prefix}

prepend-path    PATH    \$prefix/bin:\$prefix/sbin
# FIXME: Prepend dreckly to existing man path
prepend-path    MANPATH         \$prefix/man:/usr/share/man
prepend-path    MODULEPATH      \$sys_dir/etc/modulefiles

setenv          DRECKLY          \$prefix
setenv          DRECKLY_INCLUDE  \$prefix/include
setenv          DRECKLY_LIB      \$prefix/lib
EOM

# GCC scripts and modules
gcc=7   # Lowest supported
while [ -e $dreckly_dir/lang/gcc$gcc ]; do
    cat << EOM > ${sys_dir}/etc/gcc$gcc.sh
# Generated by auto-dreckly-setup
# Assumes dreckly already in path
# Use alone only if you know what you're doing
if ! echo \$PATH | fgrep -q "${prefix}/gcc$gcc/bin:"; then
    dreckly=$prefix
    export dreckly
    
    PATH=${COMPILER_PATH_COLON}\$DRECKLY/gcc$gcc/bin:\$PATH
    export PATH
    # dreckly gcc man pages broken
    # MANPATH=\$DRECKLY/gcc$gcc/man:\$DRECKLY/man:\$DRECKLY/share/man:/usr/share/man
    # export MANPATH
    DRECKLY_INCLUDE=\$DRECKLY/gcc$gcc/include
    export DRECKLY_INCLUDE
    DRECKLY_LIB=\$DRECKLY/gcc$gcc/lib
    export DRECKLY_LIB
fi
EOM

    cat << EOM > ${sys_dir}/etc/gcc$gcc.csh
# Generated by auto-dreckly-setup
# Assumes dreckly already in path
# Use alone only if you know what you're doing
echo \$PATH | fgrep -q "${prefix}/gcc$gcc/bin:"
if ( \$status != 0 ) then
    setenv DRECKLY   $prefix
    
    setenv PATH                  ${COMPILER_PATH_COLON}\$DRECKLY/gcc$gcc/bin:\$PATH
    # dreckly gcc man pages broken
    # setenv MANPATH             \$DRECKLY/gcc$gcc/man:\$DRECKLY/man:\$DRECKLY/share/man:/usr/share/man
    setenv DRECKLY_GCC_INCLUDE   \$DRECKLY/gcc$gcc/include
    setenv DRECKLY_GCC_LIB       \$DRECKLY/gcc$gcc/lib
endif
EOM

    cat << EOM > ${sys_dir}/etc/modulefiles/dreckly/gcc$gcc
#%Module1.0#####################################################################
proc ModulesHelp { } {
    puts stdout "\n\tdreckly gcc$gcc"
    puts stdout "\tThis module prepends the dreckly gcc$gcc directories to"
    puts stdout "\tappropriate environment variable(s)."
}

module-whatis   "dreckly gcc$gcc"

set     version ${dist_suffix#-}
set     prefix  ${prefix}

prepend-path    PATH    \$prefix/gcc$gcc/bin
# dreckly gcc man pages broken
# prepend-path    MANPATH \$prefix/gcc$gcc/man:\$prefix/man:/usr/share/man

setenv          DRECKLY_GCC_INCLUDE  \$prefix/gcc$gcc/include
setenv          DRECKLY_GCC_LIB      \$prefix/gcc$gcc/lib
EOM
    gcc=$(($gcc + 1))
    if [ $gcc = 11 ]; then  # No gcc11 in dreckly
	gcc=$(($gcc + 1))
    fi    
done    # while [ -e $dreckly_dir/lang/gcc$gcc ]

if [ -n "$base_gcc" ]; then
    ln -f ${sys_dir}/etc/$base_gcc.sh ${sys_dir}/etc/gcc-base.sh
    ln -f ${sys_dir}/etc/$base_gcc.csh ${sys_dir}/etc/gcc-base.csh
    ln -f ${sys_dir}/etc/modulefiles/dreckly/$base_gcc \
	${sys_dir}/etc/modulefiles/dreckly/gcc-base
fi

##########################################################################
#   Generate profile.d scripts for updating MODULEPATH
##########################################################################

profile_dir="$sys_dir/etc/profile.d"
mkdir -p $profile_dir
# Should come alphabetically after modules.sh and modules.csh
module_path_script=modulez`echo $prefix | tr '/' '-'`
cat << EOM > $profile_dir/$module_path_script.sh
MODULEPATH=\${MODULEPATH}:$sys_dir/etc/modulefiles
export MODULEPATH
EOM
cat << EOM > $profile_dir/$module_path_script.csh
setenv MODULEPATH \${MODULEPATH}:$sys_dir/etc/modulefiles
EOM
chmod 644 $profile_dir/$module_path_script*

# Update PATH for installing packages below
. ${sys_dir}/etc/dreckly.sh

# Basic instructions on installing a package
make=bmake

printf 'umask for dreckly builds? [022] '
read dreckly_umask
if [ 0$dreckly_umask = 0 ]; then
    dreckly_umask=022
fi
cat << EOM2 > $prefix/bin/safe-bmake
#!/bin/sh -e

if ! pwd -P | fgrep -q $dreckly_dir/; then
    cat << EOM
    
			    ===== Error =====

You are running \$(which safe-bmake) from the wrong directory.
It should only be used from within $dreckly_dir/.
Load the correct environment module so that you are using the appropriate
bmake for \$(pwd) or go to $dreckly_dir/.

EOM
    exit 1
fi

umask $dreckly_umask
bmake "\$@"
EOM2

ln -sf $prefix/bin/safe-bmake $prefix/bin/sbmake
chmod 755 $prefix/bin/*bmake

cat << EOM

============================================================================
The pkgsrc-wip (work in progress) project is a worldwide centralized
repository of packages currently under development.  You can use the
packages here to test the latest features of software or get access to
packages that don't yet exist in the official dreckly collection.

You can also contribute your own packages and bug fixes.

EOM
if [ -z "$GCC_VER" ]; then
    printf "Install pkgsrc-wip? y/[n] "
    read install_wip
else
    install_wip=n
fi

if [ 0$install_wip = 0y ]; then
    cd $dreckly_dir
    
    # git sometimes returns non-zero status when it succeeded
    set +e
    if [ -d wip ]; then
	printf "pkgsrc-wip alreading installed.\n"
    else
	cat << EOM

If you have a pkgsrc-wip account, you can use it to check out pkgsrc-wip,
the work-in-progress category of dreckly packages.

If not, you can check it out anonymously.  This is the default if you just
press Enter.

EOM

	# NOTE: This is a duplicate of auto-pkgsrc-wip-checkout.
	# It is here so that this script can work as a standalone.
	# Be sure to keep this in sync with the separate script!
	printf "pkgsrc-wip username? [none] "
	read username
	if [ 0$username = 0 ]; then
	    $GIT clone git://wip.pkgsrc.org/pkgsrc-wip.git wip
	else
	    $GIT clone $username@wip.pkgsrc.org:/pkgsrc-wip wip
	fi
    fi
    set -e
fi

# Set up package server if necessary
if [ -e /etc/redhat-release ]; then
    release=`cat /etc/redhat-release`
    release=${release%%.*}
    release=${release##*release }
    os=RHEL$release
elif [ $(uname) = Darwin ]; then
    os=$(uname)$(uname -r | cut -d '.' -f 1)
else
    os=$(uname)-$(uname -r)
fi

if [ -z "$GCC_VER" ]; then
    cat << EOM

============================================================================

If you are using an operating system and PREFIX for which there are
binary packages, enter the full package server URL(s) here, e.g.:

    https://mirror1.hpc.uwm.edu

The default PKG_PATH will be set to

    <URL>/dreckly/packages/$prefix/$os/All

Edit

    $sys_dir/etc/pkg_install.conf

if this is incorrect.

EOM

    cat << EOM

Enter a binary package server name (include http:// or https://), or
just press enter if you won't be using binary packages.

EOM
    read package_server
    if [ 0$package_server != 0 ]; then
	pkg_path=${pkg_path}$package_server/dreckly/packages$prefix/$os/All\;
	pkgin_path="${pkgin_path}$package_server/dreckly/packages$prefix/$os/All\n"
    fi
    
    if [ 0$pkg_path != 0 ]; then
	printf "PKG_PATH=$pkg_path\n" >> $sys_dir/etc/pkg_install.conf
    
	# Rebuild pkg_install with SSL support
	cd $dreckly_dir/pkgtools/pkg_install
	bmake clean
	bmake clean-depends
	bmake replace ALLOW_VULNERABLE_PACKAGES=yes
	
	# Install numerous deps to save time
	pkg_add pkgin
	# unset PKG_PATH
	
	# Reinstall libfetch and pkgin from source to enable SSL.
	# mk.conf should contain "PKG_OPTIONS.libfetch=inet6 openssl" by now
	pkg_delete -f libfetch pkgin
	save_cwd=`pwd`
	cd $dreckly_dir/pkgtools/pkgin
	bmake clean
	bmake clean-depends
	bmake install
	if [ $? = 0 ]; then
	    printf "${pkgin_path}" >> $sys_dir/etc/pkgin/repositories.conf
	    pkgin update
	    cat << EOM

Pkgin initialized successfully.  You can use pkgin to install and remove
binary packages, list available packages, etc.  Run "man pkgin" for details.

EOM
	    if [ -n "$base_gcc" ]; then
		pkgin -y install $base_gcc
	    fi
	else
	    printf "Failed to install pkgin.\nCheck $sys_dir/etc/pkg_install.conf.\n"
	fi
	cd $save_cwd
	pause
    fi

    cat << EOM
==============================================================================
Unlike some other package managers, dreckly does not install any specific
certificates automatically.  Instead, it is left to the user to decide which
certificates should be trusted.

Among the most common lists of trusted certificates are those published by
Mozilla.  These are available as the following dreckly packages:

    security/mozilla-rootcerts
    security/mozilla-rootcerts-openssl

Note that these packages include certificates that are required for full
functionality in curl, git, install.packages() in the R language, and
possibly other programs you will install via dreckly.

They can be installed at any time, but doing it now might prevent problems
for all users of this system.

EOM
    printf "Install Mozilla certs now? y/[n] "
    read install_certs
    if [ 0$install_certs = 0y ]; then
	save_cwd=$(pwd)
	cd $dreckly_dir/security/mozilla-rootcerts && bmake clean install
	# mozilla-rootcerts-openssl won't install on NetBSD
	if [ $(uname) != NetBSD ] || [ $(id -un) = root ]; then
	    cd $dreckly_dir/security/mozilla-rootcerts-openssl
	fi
	if ! bmake clean install; then
	    printf "Warning: mozilla-rootcerts-openssl failed.\n"
	    pause
	fi
	cd $save_cwd
    fi

    cat << EOM

********************************** WARNING **********************************

The bmake binaries installed by dreckly are patched to install packages under
the PREFIX of the tree in which they are built, regardless of the current
working directory from which you run them.  For example, if you run
/usr/pkg-2020Q3/bin/bmake from /usr/dreckly-2019Q1, it will build packages
from /usr/dreckly-2019Q1 and install them under /usr/pkg-2020Q2.

This will likely cause serious problems, largely due to incompatible versions
of dependency packages.  It is therefore critical to ensure that your PATH is
always correct for the tree in which you are building.

It is strongly recommended that you use "safe-bmake" or the abbreviation
"sbmake" to build and install dreckly packages.  This wrapper, automatically
generated by auto-dreckly-setup, performs a simple check to ensure that you
are using the correct bmake binary for the tree in which you are building.

EOM
    pause
    
    cat << EOM
============================================================================
Users running sh-compatible shells can use the following to configure the
environment for this installation:

    . ${sys_dir}/etc/dreckly.sh

Users running csh-compatible shells can use the following:

    source ${sys_dir}/etc/dreckly.csh

On systems with the "module" command, users can use the following instead
of one of the commands above:

    module load ${sys_dir}/etc/modulefiles/dreckly/${dist_suffix#-}
============================================================================
EOM
    pause
    
    cat << EOM
============================================================================
To install a package, type:

    cd $dreckly_dir/<category>/<package>
    safe-bmake install

Ex.
    cd $dreckly_dir/math/blas
    safe-bmake install
============================================================================
EOM
    pause
    
    cat << EOM
============================================================================
After setting the environment using one of the commands above, to compile
and link programs using libraries installed by dreckly, use:

    -I\$DRECKLY_INCLUDE
    -L\$DRECKLY_LIB

Ex. Assuming your Makefile uses CFLAGS for compiling and LFLAGS for link:

    make CFLAGS="-Wall -g -I\$DRECKLY_INCLUDE" LFLAGS="-L\$DRECKLY_LIB"
============================================================================
For more information, go to https://www.netbsd.org/docs/pkgsrc/
============================================================================
EOM
    pause
    
    cat << EOM
============================================================================
You can keep your dreckly tree up-to-date by periodically running the
following commands:

    cd $dreckly_dir
    $GIT pull

The devel/scmcvs package provides a cvs command in case your system does
not already have one.

To update your installed packages after a cvs update, there are tools such
as

    pkgtools/pkg_check
    pkgtools/pkg_rolling-replace

If there are binary packages for this installation, you may also be able to
use

    pkgin upgrade
============================================================================
EOM

    # Install dreckly guide onto desktop
    if [ -e $HOME/Desktop ] && [ ! -e $HOME/Desktop/Guides/dreckly.pdf ]; then
	PATH=$PATH:/usr/local/bin   # Find curl on BSD
	export PATH
	mkdir -p $HOME/Desktop/Guides
	cd $HOME/Desktop/Guides
	printf "Fetching manual...\n"
	if $fetch_cmd https://www.netbsd.org/docs/pkgsrc/pkgsrc.pdf; then
	    printf "A copy of the dreckly guide has been placed on your desktop.\n"
	fi
    fi
else
    printf "GCC_VER is set.\n"
    pause
fi

# Generate bootstrap kit
cd $start_dir
bootstrap_archive=`echo dreckly-$os-$compiler$prefix.tgz | tr / -`
if [ ! -e $bootstrap_archive ]; then
    printf "Creating bootstrap kit: $bootstrap_archive...\n"
    $tar zcf $bootstrap_archive $prefix $dreckly_dir $sys_dir || true
    cat << EOM

Bootstrap image saved to $bootstrap_archive.

You can unpack this file to / on other identical $(uname) systems in order to
quickly replicate this installation.

EOM
    pause
else
    printf "$bootstrap_archive already exists.\n"
fi

if [ -n "$GCC_VER" ]; then
    # Now bootstrap again using the dreckly GCC tree
    if [ ! -e $prefix/gcc$GCC_VER/bin ]; then
	(cd $dreckly_dir/lang/gcc$GCC_VER && time bmake clean install)
    fi
    COMPILER_PATH=$prefix/gcc$GCC_VER/bin
    export COMPILER_PATH
    $0
else
    auto_software=`auto-ask auto_admin "Run auto-software-manager now to install additional software? (y/n)" y`
    if [ $auto_software = y ]; then
	(cd $dreckly_dir/sysutils/auto-admin && bmake clean install clean)
	auto-software-manager
	cat << EOM

Run auto-software-manager for a menu interface to dreckly.

EOM
    fi
fi

