uci-docker-build/lib/helpers.lib

104 lines
3.0 KiB
Plaintext
Raw Normal View History

#!/bin/bash
isAbsPath() {
if [[ "${1:0:1}" == / || "${1:0:2}" == ~[/a-z] ]]
then
echo "true"
return 0
else
return 1
fi
}
sed_ignore_comments () {
cmd="sed -r 'h;s/[^#]*//1;x;s/#.*//;${1};G;s/(.*)\n/\1/'"
if (( $# == 2 )) ; then
eval $cmd <<< "$2"
else
eval $cmd < /dev/stdin
fi
}
clean_env_file () {
local compact
# -c will also remove comments and all empty lines
[[ $1 == "-c" ]] && compact=true && shift 1
#
# remove trailing spaces | remove double quotes
# | remove blanks after equals and quote value | remove any spaces before afer =
# remove blank lines | remove comment lines if requested
cat $1 | sed_ignore_comments s/\\s*$//g | sed_ignore_comments s/\"//g \
| sed_ignore_comments s/\(=[[:blank:]]*\)\(.*\)/\\1\"\\2\"/ \
| sed_ignore_comments s/\\s*=\\s*/=/g \
| sed -rz 's/^\n+//; s/\n+$/\n/g' | if [[ $compact ]]; then grep -v '^#' | grep -v "^$" ; else cat; fi
}
env_file () {
env=${1:-.env}
[[ -f "${env}" ]] && { echo $env; return 0; } # || echo not $env
[[ -f "${env}.env" ]] && { echo "${env}.env"; return 0; } # || echo not ${env}.env
[[ -f "${env}/.env" ]] && { echo "${env}/.env"; return 0; } # || echo not ${env}/.env
return 1
}
read_env_file() {
while read line; do
evar=$(echo $line | cut -d '=' -f1)
if [[ ! ${!evar} ]]; then
# echo DECLARE $evar via $line
if declare -gx "$(echo "${line}" | sed 's/\"//g' )"; then
echo loaded: ${evar}=${!evar}
else
echo error setting $evar
return 1
fi
else
echo $evar already set to ${!evar}
fi
done < <(clean_env_file -c $1)
}
source_env_file () {
local default
if efile=$(env_file $1); then
[[ $efile == ".env" ]] && default=true
[[ ! $(isAbsPath $efile) ]] && efile=$(realpath $efile)
echo -e "\e[1;37m********************\e[0;37m"
echo loading build environment with environment file
echo $efile
echo ----------------
cat $efile
echo ----------------
if read_env_file "$efile"; then
[[ $default ]] && echo -e "\e[1;31mNOTE: sourced default .env file in present directory\e[0;37m"
echo -e "\e[1;37m********************\e[0;37m"
else
echo error occured while loading environment file
echo $efile
echo exiting
echo -e "\e[1;37m********************\e[0;37m"
return 2
fi
else
if [[ $efile ]]; then
echo unable to find an environment file with passed ${1}
else
echo unable to find default environment file .env
echo using passed and default build options
fi
return 2
fi
}
docker_image_distro() {
local temp=/tmp/os-release.tmp
docker create --name dummy $1 > /dev/null
docker cp -L dummy:/etc/os-release $temp
docker rm -f dummy > /dev/null
echo $(cat $temp | tr [:upper:] [:lower:] | grep -Poi '(debian|ubuntu|red hat|centos|arch|alpine)' | uniq)
rm $temp
}
(return 0 2>/dev/null) || docker_image_distro $@