tuxflotte-installer/scripts/modules/20_profile_selection.sh

118 lines
2.9 KiB
Bash
Executable File

#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"
readonly SCRIPT_NAME
readonly SERVER_RESPONSE_FILE="/run/tuxflotte/server/response.json"
readonly RUNTIME_DIR="/run/tuxflotte/assignment"
readonly PROFILE_FILE="${RUNTIME_DIR}/profile.json"
log() {
printf '[%s] %s\n' "${SCRIPT_NAME}" "$*"
}
fatal() {
printf '[%s] FEHLER: %s\n' "${SCRIPT_NAME}" "$*" >&2
exit 1
}
require_root() {
if [[ "${EUID}" -ne 0 ]]; then
fatal "Das Profilauswahlmodul muss als root ausgeführt werden."
fi
}
prepare_runtime() {
install -d -m 0700 "${RUNTIME_DIR}"
rm -f -- "${PROFILE_FILE}"
}
validate_server_response() {
[[ -r "${SERVER_RESPONSE_FILE}" ]] ||
fatal "Serverantwort nicht gefunden: ${SERVER_RESPONSE_FILE}"
jq --exit-status . "${SERVER_RESPONSE_FILE}" >/dev/null ||
fatal "Serverantwort enthält kein gültiges JSON."
jq --exit-status '
.success == true
and (.profiles | type == "array")
and (.profiles | length > 0)
' "${SERVER_RESPONSE_FILE}" >/dev/null ||
fatal "Serverantwort enthält keine auswählbaren Profile."
}
show_profiles() {
local index=1
local profile
log "Verfügbare Provisioning-Profile:"
while IFS= read -r profile; do
printf '\n'
printf ' %d) %s\n' \
"${index}" \
"$(jq -r '.label' <<<"${profile}")"
printf ' Distribution: %s %s\n' \
"$(jq -r '.distribution' <<<"${profile}")" \
"$(jq -r '.version' <<<"${profile}")"
printf ' %s\n' \
"$(jq -r '.description // ""' <<<"${profile}")"
((index += 1))
done < <(jq -c '.profiles[]' "${SERVER_RESPONSE_FILE}")
}
select_profile() {
local profile_count
local selection
profile_count="$(jq '.profiles | length' "${SERVER_RESPONSE_FILE}")"
while true; do
printf '\n'
read -r -p "Profil auswählen [1-${profile_count}]: " selection
if [[ "${selection}" =~ ^[0-9]+$ ]] &&
((selection >= 1 && selection <= profile_count)); then
break
fi
log "Ungültige Auswahl."
done
jq \
--argjson index "$((selection - 1))" \
'{
schema_version: 1,
profile: .profiles[$index]
}' \
"${SERVER_RESPONSE_FILE}" >"${PROFILE_FILE}"
chmod 0600 "${PROFILE_FILE}"
jq --exit-status '
.schema_version == 1
and (.profile | type == "object")
and (.profile.id | type == "string")
and (.profile.id | length > 0)
' "${PROFILE_FILE}" >/dev/null ||
fatal "Ausgewähltes Profil konnte nicht gültig gespeichert werden."
log "Profil $(jq -r '.profile.id' "${PROFILE_FILE}") wurde ausgewählt."
log "Profilauswahl wurde unter ${PROFILE_FILE} gespeichert."
}
main() {
require_root
prepare_runtime
validate_server_response
show_profiles
select_profile
}
main "$@"