#!/bin/ksh -xe
umask 022

ARGS="$@"

trap abort 1 2 3 6 9 11
abort() { echo "Abort with >$0 $ARGS< on $(date)" >> /tmp/obsdmake.log; }

JOBS="${JOBS:=$(sysctl -n hw.ncpuonline)}"

export CCACHE_DIR="/var/ccache"
export CCACHE_SLOPPINESS="locale,time_macros,random_seed,file_stat_matches,pch_defines"
export CCACHE_MAXSIZE=20G
export CCACHE_NOHASHDIR=

export CMAKE_CXX_COMPILER_LAUNCHER=ccache
export CMAKE_C_COMPILER_LAUNCHER=ccache

export CC="/opt/ccache/bin/cc $EXTRAFLAGS"
export CXX="/opt/ccache/bin/c++ $EXTRAFLAGS"

if [ -z "$1" ]; then
    echo "Usage: ${0} [kernel, base, xenocara, release, all] [clean]"
    exit 2
fi

echo "Start with >$0 $ARGS< on $(date)" >> /tmp/obsdmake.log

doas mkdir -p /usr/obj /usr/xobj
doas chown build /usr/obj /usr/xobj

mkkernel() {
    set -xe
    cd /sys/arch/$(machine)/compile/GENERIC.MP
    doas make clean
    doas make obj
    doas make config
    time doas -u build make -j${JOBS}
    doas make install
    doas what /bsd
    doas ln -f /bsd.booted /bsd.backup
}

mkbase() {
    set -xe
    cd /usr/src
    doas make obj
    doas make -j${JOBS} build
    doas make install
    doas sysmerge
    cd /dev
    doas ./MAKEDEV all
}

mkxenocara() {
    set -xe
    doas chown -R sdk /usr/xenocara
    cd /usr/xenocara
    doas make clean
    doas make bootstrap
    doas make obj
    doas make -j${JOBS} build
    doas make install
}

mkrelease() {
    set -xe
    doas mkdir -p /data/{OpenBSD,Release}
    doas chown -R build /data
    doas chmod -R 700 /data

    export DESTDIR=/data/OpenBSD
    export RELEASEDIR=/data/Release
    export RELDIR=/data/Release
    export RELXDIR=/data/Release

    cd /usr/src/etc
    doas make release
    cd /usr/src/distrib/sets
    doas sh checkflist

    cd /usr/xenocara
    doas make release
    doas make checkdist

    cd /usr/src/distrib/$(machine)/iso
    doas make
    doas make install
}

kernelclean() {
    cd /usr/src && doas make clean
}
baseclean() {
    doas rm -rf /usr/obj/{,.}*
}
xenocaraclean() {
    doas rm -rf /usr/xobj/{,.}*
}
releaseclean() {
    doas rm -rf /data/OpenBSD/{,.}*
    doas rm -rf /data/Release/{,.}*
}
allclean() {
    kernelclean
    baseclean
    xenocaraclean
    releaseclean
}

if [ "$2" == "clean" ]; then
    case "$1" in
        kernel) kernelclean; ;;
        base) baseclean; ;;
        xenocara) xenocaraclean; ;;
        release) releaseclean; ;;
        all) allclean; ;;
    esac
    exit 0;
fi

case "$1" in
    kernel) mkkernel; ;;
    base) mkbase; ;;
    xenocara) mkxenocara; ;;
    release) mkrelease; ;;
    all) mkkernel; mkbase; mkxenocara; ;;
esac

echo "Finished with >$0 $ARGS< on $(date)" >> /tmp/obsdmake.log
sync
