#!/usr/bin/env bash source ./common.d/variables.sh log() { case "$2" in error) printf "\e[1m\e[31mERROR:\e[0m \e[1m%s\e[0m\n" "$1">&2;; internal) printf "\e[1m\e[96m >>\e[0m \e[1m%s\e[0m\n" "$1">&2;; ierror) printf "\e[1m\e[31m >>\e[0m \e[1m%s\e[0m\n" "$1">&2;; *) printf "\e[1m\e[92m>>>\e[0m \e[1m%s\e[0m\n" "$1">&2;; esac } mkdir_if_not_exists () { [ -d "$1" ] && return 0 [ -f "$1" ] && rm -f "$1" mkdir "$1" } umount_if_mouted() { [ ! -d "$1" ] && return 1 if grep -qs "$(realpath "$1")" /proc/mounts; then umount -R "$1" return $? else return 0 fi } umount_force() { [ ! -d "$1" ] && return 1 for run in {1..5}; do umount -R "$1" && break log "Failed to umount $1. Trying again after 3 seconds" ierror sleep 3 done } prepare_env() { mkdir_if_not_exists "./cache" mkdir_if_not_exists "./out" mkdir_if_not_exists "./raw" mkdir_if_not_exists "./tmp" [ ! -d "./packages" ] && { log "Packages not found. Cannot continue" error exit 4 } } require () { which "$1" > /dev/null 2>&1 || { log "$1 not found" error exit 1 } } # shellcheck disable=SC2161 # shellcheck disable=SC2086 arguments() { while [[ $# -gt 0 ]]; do opt="$1" shift case "$(echo ${opt} | tr '[:upper:]' '[:lower:]')" in -c | --cleanup) cleanup exit $? ;; -r | --cleanraw) cleanraw exit $? ;; -w | --cleancache) cleancache exit $? ;; -h | -help | --help) usage exit $? ;; *) export LNIBUILD="$opt" break 2 ;; esac done } usage() { log "Usage commands:" cat < EOF return 0 } # shellcheck disable=SC2162 cleanup() { source ./common.d/build_functions.sh find ./tmp/ -mindepth 1 -maxdepth 1 | read || { [ -z ${quiet+x} ] && log "Nothing to clean" error return 0 } for d in ./tmp/*/; do log "Unmounting $d" detach_chroot "$d" umount "$d/boot/simpleinit" umount "$d/boot/efi" umount "$d" rm -d "$d" done return 0 } cleanraw() { find ./raw/ -mindepth 1 -maxdepth 1 | read || { [ -z ${quiet+x} ] && log "Nothing to clean" error return 0 } rm ./raw/* -f && log "Done!" } cleancache() { find ./cache/ -mindepth 1 -maxdepth 1 | read || { [ -z ${quiet+x} ] && log "Nothing to clean" error return 0 } rm ./cache/* -f && log "Done!" } # shellcheck disable=SC2317 _shutdown() { quiet='' cleanup if [ -z ${1+x} ]; then exit 0 else exit "$1" fi } sigterm_handler() { sig=$? printf "\e[1m\e[31m>>\e[0m \e[1m%s\e[0m\n" "Shutdown signal received." _shutdown $sig } trap 'trap " " SIGINT SIGTERM SIGHUP; kill 0; wait; sigterm_handler' SIGINT SIGTERM SIGHUP