abinfo "Building metasploit-framework bundle ..."
bundle config set --local deployment 'true'

# FIXME: Compiling the Nokogiri component on the Loongson 3 platform results in the following error:
# `Invalid configuration 'mips64el-aosc-linux-abi64': OS 'abi64' not recognized`. 
# Use the `--use-system-libraries` flag to bypass this issue.
if ab_match_arch loongson3; then
    bundle config set --local build.nokogiri "--use-system-libraries"
fi

abinfo "Installing metasploit-framework ..."
bundle install -j"$(nproc)" --no-cache --verbose
install -dv "$PKGDIR"/usr/share/metasploit-framework
install -dv "$PKGDIR"/usr/bin

abinfo "Removing unnecessary files ..."
rsync -av --exclude ".git" --exclude abdist --exclude abdist-dbg --exclude autobuild \
    --exclude ".github" --exclude "Dockerfile" --exclude "/kubernetes" --exclude "/test" \
    "$SRCDIR"/ "$PKGDIR"/usr/share/metasploit-framework/

rm -rv "$PKGDIR"/usr/share/metasploit-framework/vendor/bundle/ruby/*/cache
find "$PKGDIR"/usr/share/metasploit-framework/ -name "*.log" -print -delete
find "$PKGDIR"/usr/share/metasploit-framework/vendor/bundle -name "gem_make.out" -print -delete

abinfo "Creating wrapper scripts ..."
for f in "$PKGDIR"/usr/share/metasploit-framework/msf*; do
    if [ -f "$f" ] && [ -x "$f" ]; then
        _msffile="$PKGDIR/usr/bin/$(basename "$f")"
        cat > "${_msffile}" << EOF
#!/bin/sh
BUNDLE_GEMFILE=/usr/share/metasploit-framework/Gemfile exec bundle exec ruby /usr/share/metasploit-framework/$(basename "$f") "\$@"
EOF
        chmod -v 755 "${_msffile}"
    fi
done

abinfo "Removing executable for launching automatic updates ..."
rm -v "$PKGDIR"/usr/bin/msfupdate
