#!/usr/bin/env bash
#
# Create a new jail
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

: ${JAIL_MOUNTPOINT:="{{ jail_zfs_dataset_mountpoint }}"}

function die {
    echo >&2 "$@"
    exit 1
}

[ "$#" -eq 2 ] || die "1 argument required, $# provided"

JAIL_NAME="$2"
export DESTDIR="${JAIL_MOUNTPOINT}/$JAIL_NAME"

function by_src {
    cd /usr/src
    make -j 16 buildworld
    make installworld DESTDIR=$DESTDIR
    make distribution DESTDIR=$DESTDIR
    switch_to_latest_packages
}

function by_bin {
    DESTRELEASE=13.2-RELEASE
    DESTARCH=`uname -m`
    SOURCEURL=http://ftp.freebsd.org/pub/FreeBSD/releases/$DESTARCH/$DESTRELEASE/
    for component in base ports; do fetch $SOURCEURL/$component.txz -o - | tar -xf - -C "$DESTDIR" ; done
    switch_to_latest_packages
}

function by_pkg {
    # current https://pkg.freebsd.org/FreeBSD:15:amd64/base_latest
    # 14/stable https://pkg.freebsd.org/FreeBSD:14:amd64/base_latest
    # 14.1 https://pkg.freebsd.org/FreeBSD:14:amd64/base_release_1
    local config
    config=$(cat <<EOF
base: {
    url: "https://pkg.freebsd.org/FreeBSD:14:amd64/base_release_1",
    mirror_type: "none",
    enabled: yes,
    priority: 100
}
EOF
             )
    IGNORE_OSVERSION=yes pkg --rootdir "$DESTDIR" --config <(cat <<<"$config") install --repository base --yes --glob 'FreeBSD-*'
    switch_to_latest_packages
    local in_jail_config
    in_jail_config=$(cat <<EOF
base: {
    url: "pkg+https://pkg.freebsd.org/\${ABI}/base_release_1",
    mirror_type: "srv",
    signature_type: "fingerprints",
    fingerprints: "/usr/share/keys/pkg",
    enabled: yes,
    priority: 100
}
EOF
             )
    cat > "$DESTDIR/usr/local/etc/pkg/repos/pkgbase.conf" <<<"$in_jail_config"
    # Post-install remove extra packages
    # pkg remove --glob 'FreeBSD-*-lib32*' 'FreeBSD-*-dbg*' FreeBSD-src
}

function switch_to_latest_packages {
    local latest_pkg
    latest_pkg=$(cat <<EOF
FreeBSD: {
  url: "pkg+http://pkg.FreeBSD.org/\${ABI}/latest"
}
EOF
              )
    mkdir -p "$DESTDIR/usr/local/etc/pkg/repos"
    cat > "$DESTDIR/usr/local/etc/pkg/repos/FreeBSD.conf" <<<"$latest_pkg"
}

if [ "$1" = "src" ]; then
    by_src
elif [ "$1" = "bin" ]; then
    by_bin
elif [ "$1" = "pkg" ]; then
    by_pkg
else
    die "First argument must be either 'src' or 'bin', got $1"
fi