#!/usr/local/bin/cbsd
#v12.1.9
CBSDMODULE="build"
MYARG="dst"
MYOPTARG="emulator qemu"
MYDESC="Misc fixes under base hier"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

This script complements the hierarchy by adding several 
symlinks or by creating the missing dir.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}emulator${N0_COLOR}  - copy QEMU usermode files for chrooting,
             eg: emulator=qemu-arm;

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd preparebase dst=/usr/jails/basejail/base_amd64_amd64_14.0

"


. ${subrdir}/nc.subr
qemu=
. ${cbsdinit}

[ -z "${qemu}" ] && qemu=1

[ ! -d "${dst}" ] && err 1 "No such dir: ${dst}"
[ ! -d "${dst}/usr/home" ] && ${MKDIR_CMD} -m 0755 "${dst}/usr/home"
[ ! -d "${dst}/usr/ports" ] && ${MKDIR_CMD} -m 0755 "${dst}/usr/ports"
[ ! -h "${dst}/home" ] && ${LN_CMD} -sf "usr/home" "${dst}/home"
[ ! -h "${dst}/usr/bin/perl" ] && ${LN_CMD} -sf "/usr/local/bin/perl" "${dst}/usr/bin/perl"
[ ! -h "${dst}/usr/bin/perl5" ] && ${LN_CMD} -sf "/usr/local/bin/perl" "${dst}/usr/bin/perl5"
[ ! -h "${dst}/bin/zsh" ] && ${LN_CMD} -sf "/usr/local/bin/zsh" "${dst}/bin/zsh"
[ ! -h "${dst}/bin/bash" ] && ${LN_CMD} -sf "/usr/local/bin/bash" "${dst}/bin/bash"

[ -h "${dst}/compat" ] && ${RM_CMD} -f ${dst}/compat
[ ! -d "${dst}/compat" ] && ${MKDIR_CMD} -m 0755 "${dst}/compat"

[ ! -d "${dst}/usr/local" ] && ${MKDIR_CMD} -m 0755 "${dst}/usr/local"

# remove unecessary resources
[ -d "${dst}/usr/lib/debug" ] && ${RM_CMD} -rf ${dst}/usr/lib/debug

# Init PKG in basedir
# offline?
# native only?
hoster_ver=$( ${miscdir}/elf_tables --freebsdver /bin/sh )
base_ver=$( ${miscdir}/elf_tables --freebsdver ${BASE_DIR}/bin/sh )

if [ "${hoster_ver}" = "${base_ver}" ]; then
	CBSDPATH="${PATH}"
	${MOUNT_CMD} -t devfs devfs ${dst}/dev
	${CHROOT_CMD} ${dst} /bin/sh <<EOF
env ASSUME_ALWAYS_YES=yes SIGNATURE_TYPE=none IGNORE_OSVERSION=yes timeout 30 pkg  bootstrap -y -f || true
EOF
	${UMOUNT_CMD} ${dst}/dev
fi

if [ "${qemu}" = "1" ]; then
	# for qemu user mode
	[ -z "${emulator}" ] && exit 0
	[ "${emulator}" = "jail" -o "${emulator}" = "bhyve" ] && exit 0

	echo " * Copying emulator to /bin" 1>&2
	. ${subrdir}/emulator.subr
	init_usermode_emul

	[ ! -d "${dst}/bin" ] && ${MKDIR_CMD} -m 0755 -p ${dst}/bin
	[ ! -r ${emultest} ] && err 1 "${N1_COLOR}${CBSD_APP}: no such emulator: ${N2_COLOR}${emultest}${N0_COLOR}"
	emulfile=$( ${BASENAME_CMD} ${emultest} )
	[ ! -r ${dst}/bin/${emulfile} ] && ${CP_CMD} -a ${emultest} ${dst}/bin/
	[ ! -r ${dst}/bin/${emulfile} ] && err 1 "${N1_COLOR}${CBSD_APP}: unable to copy: ${N2_COLOR}cp ${emultest} ${dst}/bin/${N0_COLOR}"
fi


exit 0
