ports/main/nnd-s6-services/manage.sh

93 lines
2.3 KiB
Bash
Executable File

#!/bin/sh
export PATH="/usr/bin:/bin"
error() {
: ${ERR:=1}
echo "$@" >&2
return "$ERR"
}
alt_ab() {
if [ "$1" == "a" ]; then echo "b"; else echo "a"; fi
}
: ${S6_PATH:='/etc/s6'}
: ${S6_DIST_PATH:="$S6_PATH/dist"}
: ${S6_RC_PATH:="$S6_PATH/rc"}
: ${S6_ENV_PATH:="$S6_PATH/env"}
: ${S6_SV_PATH:="$S6_PATH/sv"}
# A/B mode, always keep last copy
DB_FRESH_ACT=""
DB_FRESH_NAC=""
cstate() {
DB_FRESH_ACT="$(readlink "$S6_SV_PATH/current" | cut -d. -f2)" # if it fails (missing), it will be empty and 'a' will be used as inactive by default
DB_FRESH_NAC="$(alt_ab "$DB_FRESH_ACT")"
}
generate() {
mkdir -p "$S6_SV_PATH" || ERR="$?" error "Failed to create sv directory"
# A/B current
if [ -d "$S6_SV_PATH/current.$DB_FRESH_NAC" ]; then
rm -rf "$S6_SV_PATH/current.$DB_FRESH_NAC" || ERR="$?" error "Failed to remove inactive database path"
fi
s6-rc-compile "$S6_SV_PATH/current.$DB_FRESH_NAC" "$S6_RC_PATH" || ERR="$?" error "Failed to compile current s6 database"
}
update() {
s6-rc-update "$S6_SV_PATH/current.$DB_FRESH_ACT" || ERR="$?" error "Failed to update live state of the database"
}
swap() {
[ -d "$S6_SV_PATH/current.$DB_FRESH_NAC" ] || error "There's no database to switch to"
ln -sfn "current.$DB_FRESH_NAC" "$S6_SV_PATH/current" || ERR="$?" error "Failed to update A/B current symlink"
}
dist() {
SDIR="$S6_DIST_PATH/rc" DPATH="$S6_RC_PATH" distdefs
SDIR="$S6_DIST_PATH/env" DPATH="$S6_ENV_PATH" distdefs
# Remove any dangling invalid symlinks
find -L /etc/s6/rc/ -type l -exec rm -v -- {} +
}
distdefs() {
[ -z "$SDIR" ] && error "SDIR not defined"
[ -z "$DPATH" ] && error "DPATH not defined"
for cdir in "$SDIR"/*; do
local srv="${cdir##*/}"
local dsv="$DPATH/$srv"
if [ ! -e "$dsv" ]; then
ln -sv "$cdir" "$dsv" || ERR="$?" error "Failed to create reference"
fi
done
}
custom() {
local SVC="$1"
local target="$S6_RC_PATH/$SVC"
[ -e "$target" ] || error "Service $SVC doesn't exist"
[ -h "$target" ] || error "Service $SVC is already a custom instance"
rm -rf "$target"
cp -r "$S6_DIST_PATH/rc/$SVC" "$target"
local target="$S6_ENV_PATH/$SVC"
if [ -e "$target" ]; then
rm -rf "$target"
cp -r "$S6_DIST_PATH/env/$SVC" "$target"
fi
}
cmd="$1"
shift
cstate
case "$cmd" in
generate|update|swap|dist|custom) eval "$cmd" $@;;
*) error "Invalid command $cmd";;
esac