#!/bin/sh -e

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


##########################################################################
#   Function description:
#       Ask user to select a snapshot
#
#   History:
#   Date        Name        Modification
#   2016-01-04  Jason Bacon Begin
#
#   Git version:
#   replace-me
##########################################################################

select_snapshot()
{
    cat << EOM

You must now choose a pkgsrc snapshot to install.

Quarterly snapshots such as "2016Q2" have gone through additional quality
control at the end of each quarter and contain fewer bugs.

The "current" snapshot contains the latest commits of each package.

See https://ftp.netbsd.org/pub/pkgsrc/ for a list of available snapshots.

1.. Install a quarterly snapshot
2.. Install current
3.. Install from git URL
4.. Install from a custom source tree (must already exist)

EOM
    
    selected=0
    while [ $selected = 0 ]; do
	printf "Selection? "
	read snapshot
	case $snapshot in
	1)
	    printf "Year? "
	    read year
	    printf "Quarter? "
	    read quarter
	    snapshot=pkgsrc-${year}Q$quarter
	    selected=1
	    ;;
	2)
	    snapshot=current
	    selected=1
	    ;;
	3)
	    snapshot=git
	    selected=1
	    ;;
	4)
	    snapshot=custom
	    selected=1
	    ;;
	*)
	    printf "Error: Invalid selection.\n" >> /dev/stderr
	    ;;
	esac
    done
    return 0
}


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

usage()
{
    cat << EOM

Usage: $0 [--help] [--extract-only] [boostrap-flags]

The following bootstrap flags are generated by auto-pkgsrc-setup:

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

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

EOM
    exit 1
}


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

if [ 0$1 = 0--extract-only ]; then
    EXTRACT_ONLY=yes
    shift
elif [ 0$1 = 0--help ]; then
    usage
fi

if [ $(uname) = SunOS ] && ! which gtar; 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 pkgsrc bootstrap and package builds to
ensure that most files are world-readable and certain private files are
protected.  Changing permissions on installed pkgsrc 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 pkgsrc 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"

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 gcc g++ gfortran default-jdk-headless tar curl git
    fi
fi

if [ $(uname) != NetBSD ]; then
    printf "Checking for required tools...\n"
    for tool in cc c++ java tar curl git; do
	if ! which $tool; then
	    if [ $tool = cc ] && which gcc; then
		continue;
	    elif [ $tool = c++ ] && which g++; 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 gcc g++ gfortran default-jdk-headless tar curl git

On Fedora/RHEL-based systems:

    yum install -y $YUM_TOOLS

On Illumos:

    pkg update
    reboot      # To load new boot env
    pkg install developer/gcc-10 git openjdk18 gtar

EOM
    exit 1
    fi
fi

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

# Special case: auto-pkgsrc-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 pkgsrc.

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 pkgsrc
packages.  As with all package systems, It is better if all pkgsrc
dependencies are installed by pkgsrc.  Pkgsrc does its best to ensure that
this happens, but configure scripts have minds of their own and pkgsrc cannot
control them completely.

EOM
    pause
    ;;
esac

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

============================================================================
You appear to be using MacPorts.  MacPorts and pkgsrc 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 pkgsrc 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 pkgsrc 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 pkgsrc 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 pkgsrc for your own exclusive use
on a system for which you don't have administrator rights.  If you want
to install pkgsrc 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/Pkgsrc
    default_parent=`(cd "$HOME/Pkgsrc"; pwd -P)`
else
    cat << EOM
    
============================================================================
Running as root.  Installing globally.
============================================================================

EOM
    if [ $(uname) = Darwin ]; then
	default_parent="/opt"
    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

select_snapshot

if [ $snapshot = current ]; then
    dist_suffix="-`date +%Y-%m-%d`"
else
    dist_suffix="${snapshot#pkgsrc}"
fi

cat << EOM
=============================================================================
Pkgsrc supports multiple installations on the same computer.
Auto-pkgsrc-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 pkgsrc tree under 

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

if [ $snapshot = custom ] || [ $snapshot = git ]; then
    use_dir_suffix=n
elif [ $snapshot = current ]; then
    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
else
    printf "Add suffix to installation directories? [y]/n "
    read use_dir_suffix
    if [ 0$use_dir_suffix != 0n ]; then
	printf "Suffix? [$dist_suffix] "
	read chosen_suffix
	if [ 0$chosen_suffix != 0 ]; then
	    dir_suffix="$chosen_suffix"
	else
	    dir_suffix="$dist_suffix"
	fi
    fi
fi

prefix=$parent/pkg$dir_suffix
pkgsrc_dir=$parent/pkgsrc$dir_suffix
sys_dir=$parent/pkg$dir_suffix
mk_conf=$sys_dir/etc/mk.conf

cat << EOM

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

    $prefix
    
Frameworks for building and installing will be under

    $pkgsrc_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
pkgsrc packages.  Many packages also require a Fortran compiler.  On
many systems, such as NetBSD, pkgsrc can build its own Fortran compilers.
On RHEL/CentOS, using the gfortran compiler provided via Yum works well.

If pkgsrc 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
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 pkgsrc-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; then
    if ! which gcc; then
	printf "No C compiler found.  Aborting...\n"
	exit 1
    fi
fi
if ! which c++; then
    if ! which g++; then
	printf "No C++ compiler found.  Aborting...\n"
	exit 1
    fi
fi

if [ $(uname) != NetBSD ] && [ $(uname) != SunOS ] && \
    [ $(uname) != FreeBSD ] && [ $(uname) != DragonFly ] && ! which java; 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 pkgsrc.

EOM
    printf "Continue without Java? y/[n] "
    read continue
    if [ 0$continue != 0y ]; then
	exit
    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; then
    cat << EOM

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

On RHEL compatible systems, it's best to install gfortran with

    yum install gcc-gfortran

before bootstrapping pkgsrc.

Otherwise, pkgsrc will attempt to install a Fortran compiler when needed,
using g95 as the default.  For better performance and support of newer Fortran
code, you may want to use one of the GCC packages instead of g95.

Note that the GCC packages are much larger than g95 and may not build on
all platforms.

You can change this later by setting

    PKGSRC_FORTRAN=gfortran

or

    PKGSRC_FORTRAN=g95

in $sys_dir/etc/mk.conf.
============================================================================

EOM
    printf "Continue without Fortran in the base compiler suite? [y]/n "
    read resp
    if [ 0$resp = 0n ]; then
	exit 1
    fi
    
    printf "Use GCC packages instead of g95? [y]/n "
    read use_gfortran

fi

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 pkgsrc build.

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

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

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

if [ 0$replace_frameworks = 0y ]; then
    # Download new pkgsrc dist if a new install number was provided
    if [ $snapshot = git ]; then
	save_cwd=`pwd`
	mkdir -p $parent
	cd $parent
	printf "git URL of pkgsrc tree? "
	read git_url
	git clone $git_url pkgsrc
	cd $save_cwd
    elif [ $snapshot = custom ]; then
	download='n'
	cat << EOM

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

EOM
	pause
    elif [ -e $parent/Dist/pkgsrc$dist_suffix.tar.gz ]; then
	printf "pkgsrc$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
	rm -rf $pkgsrc_dir $prefix $sys_dir
	mkdir -p $parent/Dist
	cd $parent/Dist
	rm -f pkgsrc.tar.gz
    
	fetched=no
	for dist in \
	    https://ftp.netbsd.org/pub/pkgsrc/$snapshot/pkgsrc.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 pkgsrc-yearQquarter.tar.gz
	if echo $dist | fgrep ftp.netbsd.org; then
	    mv pkgsrc.tar.gz pkgsrc$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 $pkgsrc_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 pkgsrc$dist_suffix.tar.gz
    else
	$tar --no-same-permissions -zoxf pkgsrc$dist_suffix.tar.gz
    fi
    rm -rf $pkgsrc_dir $sys_dir $prefix
    mv pkgsrc $pkgsrc_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 $pkgsrc_dir/bootstrap
    
    # Scrub env to prevent leakage of nonstandard tools into pkgsrc
    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; 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-pkgsrc-setup customizations\n\n" >> $mk_conf

    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 "PKGSRCDIR=\t\t$pkgsrc_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 pkgsrc options in mk.conf
    ######################################
    
    # Add X11_TYPE=modular tells pkgsrc 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
    
    printf "Will you be using this installation for package development? y/[n] "
    read developer
    if [ 0$developer = 0y ]; then
	if ! fgrep PKG_DEVELOPER $mk_conf; then
	    printf "PKG_DEVELOPER=\t\tyes\n" >> $mk_conf
	fi
    fi
    
    # Github and some other sites are inaccessible via ftp on Linux
    # Try to use a native tool rather than one that pkgsrc 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; then
	    cat << EOM

You must install curl via your native Linus 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 pkgsrc 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
    printf "Accept all software licenses? [y]/n "
    read skip_license_check
    if [ 0$skip_license_check != 0n ]; then
	printf "SKIP_LICENSE_CHECK=\tyes\n" >> $mk_conf
    else
	tmpfile=auto-pkgsrc-setup-license-list
	awk '{
	if ( $1 == "DEFAULT_ACCEPTABLE_LICENSES=" )
	    while ( $NF == "\\" )
	    {
		getline;
		for (c=1; c<NF; ++c) printf("%s ", $c);
	    }
	}' $pkgsrc_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
    
    cat << EOM
Allow installation of packages with known security vulnerabilities?

Not recommended on systems with untrusted users or systems on public
networks.

If you answer NO here, you can still install individual vulnerable
packages by running

    env ALLOW_VULNERABLE_PACKAGES=yes bmake install

EOM
    #printf "Allow vulnerable packages? y/[n] "
    #read allow_vulnerable
    #if [ 0$allow_vulnerable = 0y ]; then
    #    printf "ALLOW_VULNERABLE_PACKAGES=yes\n" >> $mk_conf
    #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|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-pkgsrc-setup customizations\n" >> $mk_conf

fi  # bootstrap

# FIXME: Verify that this is the minimal list of $base_gcc deps
# Pkgsrc 2017Q2 assumes a c++11 compiler.  Force RHEL 6 to build everything
# using a pkgsrc GCC instead of its native GCC 4.4.7, which has only partial
# c++11 support and does not support the -std=c++11 flag.
# Hopefully pkgsrc will handle cases like this automatically in the near
# future and this hack will no longer be needed.
#
# gmake, gsed, and libiconv are for NetBSD

if [ $(uname) = Linux ] || [ $(uname) = NetBSD ]; then
    selection=999
    while [ 0"$selection" -gt 05 ]; do
	cat << EOM
    
Select a minimum GCC version.  Many packages will not build with older
GCC suites such as the GCC 4.4 provided by RHEL/CentOS 6.  When you select
a newer compiler here, a pkgsrc gcc will be used to build all packages
except itself.

0.. None, use base compiler
1.. 7.0
2.. 8.0
3.. 9.0
4.. 10.0
5.. 12.0

EOM
	# Keep this in sync with pbulk-setup
	default_minimum=0
	printf "Selection? [$default_minimum] "
	read selection
	if [ 0$selection = 0 ]; then
	    selection=$default_minimum
	fi
	case $selection in
	0)
	    base_gcc=""
	    ;;
	1)
	    base_gcc=gcc7
	    gcc_version=7.0
	    ;;
	2)
	    base_gcc=gcc8
	    gcc_version=8.0
	    ;;
	3)
	    base_gcc=gcc9
	    gcc_version=9.0
	    ;;
	4)
	    base_gcc=gcc10
	    gcc_version=10.0
	    ;;
	5)
	    base_gcc=gcc12
	    gcc_version=12.0
	    ;;
    
	*)
	    printf "Invalid selection.\n"
	    ;;
	
	esac
    done
    
    # Keep this in sync with pbulk-setup for installations that use both
    # binary packages and build from source.
    if [ ! -z $base_gcc ]; then
	cat << EOM >> $mk_conf

.ifdef BSD_PKG_MK   # pkgsrc
.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)

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*)

# RHEL systems may have an outdated "as" that cannot translate instructions
# from current GCC code generators, so force pkgsrc 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"

# pkgsrc gcc packages don't install libgcc_s on some platforms, to
# avoid problems when mixing compiler versions.  This breaks our use
# of pkgsrc 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

cat << EOM > ${sys_dir}/etc/pkgsrc.sh
# Generated by auto-pkgsrc-setup
if ! echo \$PATH | fgrep -q "${prefix}/bin:"; then
    PKGSRC=$prefix
    export PKGSRC
    
    # Scrub PATH and LD_LIBRARY_PATH before adding pkgsrc to prevent leakage
    # RHEL 7 /bin/gcc fails with cannot find cc1, so put /usr/bin first
    PATH=/usr/bin:/usr/sbin:/bin:/sbin
    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 \$PKGSRC/man:\$PKGSRC/share/man"
    else
	if which manpath > /dev/null 2>&1; then
	    MANPATH=\$PKGSRC/man:\$PKGSRC/share/man:\$(manpath)
	    export MANPATH
	fi
    fi
    
    PATH=\$PKGSRC/bin:\$PKGSRC/sbin:\$PATH
    export PATH
    PKGSRC_INCLUDE=\$PKGSRC/include
    export PKGSRC_INCLUDE
    PKGSRC_LIB=\$PKGSRC/lib
    export PKGSRC_LIB
fi
EOM

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

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

cat << EOM > ${sys_dir}/etc/pkgsrc.csh
# Generated by auto-pkgsrc-setup
echo \$PATH | fgrep -q "${prefix}/bin:"
if ( \$status != 0 ) then
    setenv PKGSRC           $prefix
    
    # Scrub PATH and LD_LIBRARY_PATH before adding pkgsrc to prevent leakage
    # RHEL 7 /bin/gcc fails with cannot find cc1, so put /usr/bin first
    setenv PATH             /usr/bin:/usr/sbin:/bin:/sbin
    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 \$PKGSRC/man:\$PKGSRC/share/man"
    else
	which manpath >& /dev/null
	if ( \$status == 0 ) then
	    setenv MANPATH \$PKGSRC/man:\$PKGSRC/share/man:\`manpath\`
	endif
    endif
    
    setenv PATH             \$PKGSRC/bin:\$PKGSRC/sbin:\$PATH
    setenv PKGSRC_INCLUDE   \$PKGSRC/include
    setenv PKGSRC_LIB       \$PKGSRC/lib
endif
EOM

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

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

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

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

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

module-whatis   "All software installed via pkgsrc"

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

# Scrub PATH before adding pkgsrc 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 pkgsrc to existing man path
prepend-path    MANPATH         \$prefix/man:/usr/share/man
prepend-path    MODULEPATH      \$sys_dir/etc/modulefiles

setenv          PKGSRC          \$prefix
setenv          PKGSRC_INCLUDE  \$prefix/include
setenv          PKGSRC_LIB      \$prefix/lib
EOM

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

module-whatis   "All software installed via pkgsrc"

puts stderr "\n======================================================================"
puts stderr "WARNING:\n"
puts stderr "pkgsrc/${dist_suffix#-}-non-exclusive allows programs and libraries"
puts stderr "that are not part of this pkgsrc 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 pkgsrc to existing man path
prepend-path    MANPATH         \$prefix/man:/usr/share/man
prepend-path    MODULEPATH      \$sys_dir/etc/modulefiles

setenv          PKGSRC          \$prefix
setenv          PKGSRC_INCLUDE  \$prefix/include
setenv          PKGSRC_LIB      \$prefix/lib
EOM

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

    cat << EOM > ${sys_dir}/etc/gcc$gcc.csh
# Generated by auto-pkgsrc-setup
# Assumes pkgsrc 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 PKGSRC   $prefix
    
    setenv PATH                 \$PKGSRC/gcc$gcc/bin:\$PATH
    # pkgsrc gcc man pages broken
    # setenv MANPATH            \$PKGSRC/gcc$gcc/man:\$PKGSRC/man:\$PKGSRC/share/man:/usr/share/man
    setenv PKGSRC_GCC_INCLUDE   \$PKGSRC/gcc$gcc/include
    setenv PKGSRC_GCC_LIB       \$PKGSRC/gcc$gcc/lib
endif
EOM

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

module-whatis   "pkgsrc gcc$gcc"

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

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

setenv          PKGSRC_GCC_INCLUDE  \$prefix/gcc$gcc/include
setenv          PKGSRC_GCC_LIB      \$prefix/gcc$gcc/lib
EOM
    gcc=$(($gcc + 1))
    if [ $gcc = 11 ]; then  # No gcc11 in pkgsrc
	gcc=$(($gcc + 1))
    fi    
done    # while [ -e $pkgsrc_dir/lang/gcc$gcc ]

if [ ! -z $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/pkgsrc/$base_gcc \
	${sys_dir}/etc/modulefiles/pkgsrc/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/pkgsrc.sh

# Basic instructions on installing a package
make=bmake

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

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

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

EOM
    exit 1
fi

umask $pkgsrc_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 pkgsrc collection.

You can also contribute your own packages and bug fixes.

EOM
printf "Install pkgsrc-wip? y/[n] "
read install_wip
if [ 0$install_wip = 0y ]; then
    cd $pkgsrc_dir
    
    if ! which git; then
	cat << EOM

No git command found.  Skipping pkgsrc-wip install for now.

See https://pkgsrc.org/wip/ for instructions on installing it later.

EOM
	pause
    else
	# 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 pkgsrc 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
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

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>/pkgsrc/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/pkgsrc/packages$prefix/$os/All\;
    pkgin_path="${pkgin_path}$package_server/pkgsrc/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 $pkgsrc_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 $pkgsrc_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 [ ! -z $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, pkgsrc 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 pkgsrc 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 pkgsrc.

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 $pkgsrc_dir/security/mozilla-rootcerts && bmake clean install
    cd $pkgsrc_dir/security/mozilla-rootcerts-openssl
    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 pkgsrc 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/pkgsrc-2019Q1, it will build packages
from /usr/pkgsrc-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 pkgsrc packages.  This wrapper, automatically
generated by auto-pkgsrc-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/pkgsrc.sh

Users running csh-compatible shells can use the following:

    source ${sys_dir}/etc/pkgsrc.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/pkgsrc/${dist_suffix#-}
============================================================================
EOM
pause

cat << EOM
============================================================================
To install a package, type:

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

Ex.
    cd $pkgsrc_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 pkgsrc, use:

    -I\$PKGSRC_INCLUDE
    -L\$PKGSRC_LIB

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

    make CFLAGS="-Wall -g -I\$PKGSRC_INCLUDE" LFLAGS="-L\$PKGSRC_LIB"
============================================================================
For more information, go to http://www.netbsd.org/docs/pkgsrc/
============================================================================
EOM
pause

cat << EOM
============================================================================
You can keep your pkgsrc tree up-to-date by periodically running the
following commands:

    cd $pkgsrc_dir
    cvs -q update -dP

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 pkgsrc guide onto desktop
if [ -e $HOME/Desktop ] && [ ! -e $HOME/Desktop/Guides/pkgsrc.pdf ]; then
    mkdir -p $HOME/Desktop/Guides
    cd $HOME/Desktop/Guides
    printf "Fetching manual...\n"
    $fetch_cmd http://www.netbsd.org/docs/pkgsrc/pkgsrc.pdf
    printf "A copy of the pkgsrc guide has been placed on your desktop.\n"
fi

touch $parent/pkg$dir_suffix/done

# Generate bootstrap kit
cd $start_dir
bootstrap_archive=`echo pkgsrc-$os-$compiler$prefix.tgz | tr / -`
printf "Creating bootstrap kit: $bootstrap_archive...\n"
$tar zcf $bootstrap_archive $prefix $pkgsrc_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

(cd $pkgsrc_dir/sysutils/auto-admin && bmake clean install)
auto-software-manager

cat << EOM

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

EOM
