ogboot/bin/oglivecli

735 lines
31 KiB
Bash

#!/bin/bash
#/**
#@file oglivecli
#@brief Command line tool to manage ogLive clients.
#@usage oglivecli Command [Options ...]
#@param Command:
#@param help show this help
#@param version show script version
#@param config [Parameter] show configuration parameters
#@param check check system consistency
#@param convert convert old ogclient to new default ogLive client
#@param list list installed ogLive clients
#@param show all show JSON information about all installed ogLive clients
#@param show default show JSON information about ogLive client marked as default
#@param show Index|Dir show JSON information about an installed ogLive client
#@param search Index|Dir show corresponding index or directory
#@param download show a menu to download an ogLive ISO image from the OpenGnsys website
#@param download Iso download an specific ogLive ISO image from the OpenGnsys website
#@param install Iso install a new ogLive client from a downloaded ISO image
#@param uninstall Iso remove ISO image and uninstall its ogLive client
#@param uninstall Index|Dir uninstall an ogLive client
#@param get-default get index value for default ogLive client
#@param set-default Index set default ogLive client
#@param rebuild rebuild a lost configuration file
#@param assign Iso Index assign an ISO file to a JSON entry
#@param Options:
#@param Index a number, starting by 0
#@param Dir directory (relative to installation directory)
#@param Iso ISO file name (relative to download URL or download directory)
#@warning This script needs "jq" command.
#@version 1.1.0 - Initial version.
#@author Ramón M. Gómez - ETSII Univ. Sevilla
#@date 2016-12-05
#@version 1.1.1b - Use reduced directory names.
#@author Ramón M. Gómez - ETSII Univ. Sevilla
#@date 2020-01-17
#*/ ##
# Global constants definition.
PROG=$(basename "$(realpath "$0")") # Program name.
OPENGNSYS=/opt/ogboot # OpenGnsys main directory.
DOWNLOADDIR=$OPENGNSYS/lib # Directory to store ogLive images.
DOWNLOADURL="https://ognproject.evlt.uma.es/trac/downloads" # Download URL.
TFTPDIR=$OPENGNSYS/tftpboot # TFTP directory.
DEFOGLIVE="ogLive" # Default ogLive directory.
MINREL=20190601 # Mininum ogLive compatibility release.
INFOFILE=$OPENGNSYS/etc/ogliveinfo.json # Configuration file.
# Global and secondary functions.
source $OPENGNSYS/lib/ogfunctions.sh || exit 1
# Create/edit JSON file about installed ogLive clients.
function addToJson() {
local i DATA OGLIVEDIST="$1" OGLIVEKRNL="$2" OGLIVEARCH="$3" OGLIVEREV="$4"
local OGLIVEDIR=$(basename $5 2>/dev/null) OGLIVEISO=$(basename $6 2>/dev/null)
# JSON data for installed ogLive.
DATA=$(cat << EOT | jq .
{"distribution":"$OGLIVEDIST","kernel":"$OGLIVEKRNL","architecture":"$OGLIVEARCH","revision":"$OGLIVEREV","directory":"$OGLIVEDIR","iso":"$OGLIVEISO"}
EOT
)
# Check JSON file consistency.
if [ "$(jq -c keys $INFOFILE 2>/dev/null)" == '["default","oglive"]' ]; then
# Check if ogLive is defined into JSON file.
n=$(jq ".oglive | length" $INFOFILE)
for ((i=0; i<n; i++)); do
[ "$(jq ".check=$DATA | .check==.oglive[$i]" $INFOFILE)" == "true" ] && INDEX=$i
done
# Check if it needs to insert data.
if [ -z "$INDEX" ]; then
INDEX=$n
jq ".oglive |= (. + [$DATA])" $INFOFILE | sponge $INFOFILE
fi
# Show JSON entry.
jq ".oglive[$INDEX]" $INFOFILE
else
# Create new JSON file.
cat << EOT | jq . | tee $INFOFILE
{"oglive":[$DATA],"default":0}
EOT
fi
}
# Command functions.
# Convert default ogclient to a new ogLive format.
function convert() {
local OGCLIENT=ogclient OLDINFOFILE=$OPENGNSYS/doc/veroglive.txt
local OGLIVEKRNL OGLIVEDIR OGLIVEISO
[ $# -ne 0 ] && raiseError usage
[ ! -w $(dirname $INFOFILE) ] && raiseError access "Configuration file."
[ -n "$(stat -c "%N" $TFTPDIR/ogclient | awk '$3~/'$DEFOGLIVE'/ {print}')" ] && raiseError access "ogLive is already converted."
pushd $TFTPDIR >/dev/null || raiseError access "Installation directory."
[ ! -f $OGCLIENT/ogvmlinuz ] && raiseError notfound "\"ogclient\"."
# Add entry to JSON file using ogclient kernel version.
OGLIVEKRNL=$(file -bkr $OGCLIENT/ogvmlinuz | awk '/Linux/ {for(i=1;i<=NF;i++) if($i~/version/) {v=$(i+1);sub(/-.*/,"",v);print v}}')
OGLIVEDIR=$DEFOGLIVE-$OGLIVEKRNL
[ -r $OLDINFOFILE ] && OGLIVEISO="$(head -1 $OLDINFOFILE)"
addToJson "$(echo $OGLIVEISO|cut -f2 -d-)" "$OGLIVEKRNL" "i386" "${OGLIVEISO##*-}" "$OGLIVEDIR" "$OGLIVEISO.iso"
# Rename directory, link to default and clean old files.
mv -v $OGCLIENT $OGLIVEDIR
ln -vfs $OGLIVEDIR $DEFOGLIVE
rm -f $OGCLIENT
ln -vfs $DEFOGLIVE $OGCLIENT
mv -v $OGCLIENT.old $OGLIVEDIR.old 2>/dev/null
rm -fv {ogvmlinuz,oginitrd.img}{,.sum} $OLDINFOFILE
popd >/dev/null
# Delete old config file.
rm -f $OLDINFOFILE
}
# Show script configuration parameters.
function config() {
local DATA
DATA=$(cat << EOT
[
{ "param": "config-file", "description": "Configuration file", "value": "$INFOFILE" },
{ "param": "download-url", "description": "ogLive download URL", "value": "$DOWNLOADURL" },
{ "param": "download-dir", "description": "ogLive download directory", "value": "$DOWNLOADDIR" },
{ "param": "install-dir", "description": "ogLive installation directory", "value": "$TFTPDIR" },
{ "param": "default-name", "description": "Default ogLive name", "value": "$DEFOGLIVE" },
{ "param": "min-release", "description": "Minimum compatibility release", "value": "r$MINREL" }
]
EOT
)
case $# in
0) # Show all parameters.
echo "$DATA" | jq -r '.[] | .description + " (" + .param + ")," + .value' | column -ts,
;;
1) # Show specified parameter.
DATA=$(echo "$DATA" | jq -r ".[] | select(.param==\"$1\").value")
[ "$DATA" ] || raiseError notfound "\"$1\"."
echo "$DATA"
;;
*) # Usage error.
raiseError usage
;;
esac
}
# Check consistency, showing configuration problems.
function check() {
local ERR=0 AUX INST DEF
[ $# -ne 0 ] && raiseError usage
# Check for old system that needs conversion.
if [ -z "$(stat -c "%N" $TFTPDIR/ogclient | awk '$3~/'$DEFOGLIVE'/ {print}')" ]; then
echo "This server uses old ogclient, please run \"$PROG convert\" to update."
let ERR++
[ ! -f $INFOFILE ] && return $ERR
fi
# Check for other problems.
[ ! -f $INFOFILE ] && echo "Configuration file does not exists: $INFOFILE" && let ERR++
[ -f $INFOFILE -a "$(jq -c keys $INFOFILE 2>/dev/null)" != "[\"default\",\"oglive\"]" ] && echo "Format error in configuration file: $INFOFILE" && let ERR++
[ ! -e $TFTPDIR ] && echo "TFTP directory does not exist: $TFTPDIR." && let ERR++
# Check for installed ogLive clients.
INST=( $(find $TFTPDIR/ -type d -name "$DEFOGLIVE-*" -a ! -name "*.old" -printf "%f\n" | sort) )
[[ ${#INST[@]} -eq 0 ]] && echo "No ogLive clients are installed." && let ERR++
DEF=( $(jq -r .oglive[].directory $INFOFILE 2>/dev/null | sort) )
# Compare installed and defined ogLive clients.
AUX=$(comm -23 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]}))
[ -n "$AUX" ] && echo "Some ogLive are installed but not defined: ${AUX//$'\n'/, }" && let ERR++
AUX=$(comm -13 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]}))
[ -n "$AUX" ] && echo "Some ogLive are defined but not installed: ${AUX//$'\n'/, }" && let ERR++
# Compare downloaded and defined ISO images.
INST=( $(find $DOWNLOADDIR/ -type f -name "$DEFOGLIVE-*.iso" -printf "%f\n" | sort) )
DEF=( $(jq -r .oglive[].iso $INFOFILE 2>/dev/null | sort) )
AUX=$(comm -23 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]}))
[ -n "$AUX" ] && echo "Some ISOs are downloaded but not defined: ${AUX//$'\n'/, }" && let ERR++
AUX=$(comm -13 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]}))
[ -n "$AUX" ] && echo "Some ISOs are defined but not downloaded: ${AUX//$'\n'/, }" && let ERR++
# Check for new ISO files downloaded after installation.
AUX=$(jq -r '.oglive[] as $og | $og.iso + ":" + $og.directory' $INFOFILE 2>/dev/null | \
while IFS=":" read -r DEF INST; do
[ $DOWNLOADDIR/$DEF -nt $TFTPDIR/$INST ] && echo "$DEF"
done)
[ -n "$AUX" ] && echo "Some ISOs are downloaded after installation: ${AUX//$'\n'/, }" && let ERR++
AUX=$(jq -r '.oglive[] as $og | if ($og.revision[1:9] | tonumber) < '$MINREL' then $og.directory else "" end' $INFOFILE 2>/dev/null)
[ -n "$AUX" ] && echo "Some installed ogLive aren't fully compatible: ${AUX//$'\n'/, }" && let ERR++
DEF=$(jq -r ".oglive[$(getdefault)].directory" $INFOFILE 2>/dev/null)
INST=$(stat -c "%N" $TFTPDIR/$DEFOGLIVE | cut -f4 -d\')
[ "$DEF" != "$INST" ] && echo "Default ogLive is not linked to right directory: $DEF <> $INST" && let ERR++
# Print result.
[ $ERR -eq 0 ] && echo "OK!" || echo "Problems detected: $ERR"
return $ERR
}
# List installed ogLive clients.
function list() {
[ $# -ne 0 ] && raiseError usage
[ ! -r $INFOFILE ] && raiseError access "Configuration file."
# List all defined indexes, directories and check if missing.
jq -r .oglive[].directory $INFOFILE | nl -v 0 | \
awk '{system("echo -n "$0"; test -d '$TFTPDIR'/"$2" || echo -n \" (missing)\"; echo")}' | column -t
}
# Show information about an installed ogLive client.
function show() {
local INDEX
[ $# -ne 1 ] && raiseError usage
[ ! -r $INFOFILE ] && raiseError access "Configuration file."
# Show JSON entries.
case "$1" in
default) # Default index.
INDEX="[$(jq -r .default $INFOFILE)]" ;;
all) # All intries.
;;
[0-9]*) # Index.
INDEX="[$1]" ;;
*) # Directory.
INDEX="[$(search "$1" 2>/dev/null)]" || raiseError notfound "Directory \"$1\"."
;;
esac
jq ".oglive$INDEX" $INFOFILE || raiseError notfound "Index \"$1\"."
}
# Show index or directory corresponding to searching parameter.
function search() {
[ $# -ne 1 ] && raiseError usage
[ ! -r $INFOFILE ] && raiseError access "Configuration file."
# Show corresponding index or directory.
list | awk -v d="$1" '{if ($2==d) print $1; if ($1==d) print $2}' | grep . || raiseError notfound "Index/Directory \"$1\"."
}
function download() {
local OGLIVE NISOS i HTTPCODE ISOREL
# Verificar si el directorio de descarga existe y tiene permisos de escritura.
[ ! -d "$DOWNLOADDIR" ] && raiseError notfound "Directorio de descarga."
[ ! -w "$DOWNLOADDIR" ] && raiseError access "Directorio de descarga."
# Si no se proporciona ningún parámetro, mostrar el menú de descargas.
if [ -z "$1" ]; then
downloadMenu
else
local selected_name="$1"
# Obtener la lista de archivos disponibles.
OGLIVE=( $(curl -k --silent $DOWNLOADURL | grep "$DEFOGLIVE.*iso") )
# Buscar el archivo seleccionado por nombre.
OGLIVEFILE=""
for iso in "${OGLIVE[@]}"; do
if [[ "$iso" == *"$selected_name"* ]]; then
OGLIVEFILE=$iso
break
fi
done
[ -n "$OGLIVEFILE" ] || raiseError download "Nombre \"$selected_name\" inválido."
# Obtener el tamaño de descarga.
local SOURCELENGTH=$(curl -k --head --retry 5 --retry-delay 5 --max-time 30 "$DOWNLOADURL/$OGLIVEFILE" | awk -F: '/Content-Length:/ {print $2}')
[ -n "$SOURCELENGTH" ] || raiseError download "$OGLIVEFILE"
# Descargar ogLive.
local TARGETFILE="$DOWNLOADDIR/$OGLIVEFILE"
trap "rm -f $TARGETFILE" 1 2 3 6 9 15
curl -k --retry 5 --retry-delay 5 "$DOWNLOADURL/$OGLIVEFILE" -o "$TARGETFILE" || raiseError download "\"$OGLIVEFILE\"."
install "$OGLIVEFILE"
fi
}
# Muestra un menú para seleccionar y descargar un archivo ogLive ISO del sitio web de OpenGnsys.
function downloadMenu() {
local OGLIVE NISOS i HTTPCODE ISOREL
OGLIVE=( $(curl -k --silent $DOWNLOADURL | grep "$DEFOGLIVE.*iso") )
NISOS=${#OGLIVE[@]}
local downloads=()
for i in $(seq 1 $NISOS); do
local installed=false
local compatible=false
[ -e $DOWNLOADDIR/${OGLIVE[i-1]} ] && installed=true
ISOREL=${OGLIVE[i-1]##*-r}; ISOREL=${ISOREL%%.*}
[ $ISOREL -ge $MINREL ] && compatible=true
local DATA=$(jq -n \
--arg id "$i" \
--arg filename "${OGLIVE[i-1]}" \
--argjson installed "$installed" \
--argjson compatible "$compatible" \
'{id: $id, filename: $filename, installed: $installed, compatible: $compatible}')
downloads+=("$DATA")
done
jq -n --argjson downloads "$(printf '%s\n' "${downloads[@]}" | jq -s .)" \
'{downloads: $downloads}'
}
# Show a menu to select and download an ogLive ISO image from the OpenGnsys website.
function download_old() {
local OGLIVE NISOS i HTTPCODE TARGETFILE
local ISOREL
[ $# -gt 1 ] && raiseError usage
[ ! -d $DOWNLOADDIR ] && raiseError notfound "Download directory."
[ ! -w $DOWNLOADDIR ] && raiseError access "Download directory."
# Check parameter.
if [ -n "$1" ]; then
# ogLive to download.
OGLIVEFILE="$1"
else
# Show download menu.
OGLIVE=( $(curl -k --silent $DOWNLOADURL | grep "$DEFOGLIVE.*iso") )
NISOS=${#OGLIVE[@]}
echo "Available downloads (+ = installed, * = full compatibility):"
for i in $(seq 1 $NISOS); do
[ -e $DOWNLOADDIR/${OGLIVE[i-1]} ] && OGLIVE[i-1]="(+) ${OGLIVE[i-1]}"
ISOREL=${OGLIVE[i-1]##*-r}; ISOREL=${ISOREL%%.*}
[ $ISOREL -ge $MINREL ] && OGLIVE[i-1]="(*) ${OGLIVE[i-1]}"
done
select opt in "${OGLIVE[@]}"; do
[ -n "$opt" ] && OGLIVEFILE=${opt##* } && break
done
fi
# Get download size.
SOURCELENGTH=$(curl -k --head --retry 5 --retry-delay 5 --max-time 30 $DOWNLOADURL/$OGLIVEFILE | awk -F: '/Content-Length:/ {print $2}')
[ -n "$SOURCELENGTH" ] || raiseError download "$OGLIVEFILE"
# Download ogLive.
TARGETFILE=$DOWNLOADDIR/$OGLIVEFILE
trap "rm -f $TARGETFILE" 1 2 3 6 9 15
curl -k --retry 5 --retry-delay 5 --max-time 30 $DOWNLOADURL/$OGLIVEFILE -o $TARGETFILE || raiseError download "\"$OGLIVEFILE\"."
}
update_json() {
local key=$1
local value=$2
result_json=$(jq --arg key "$key" --arg value "$value" '.[$key] = $value' <<< "$result_json")
}
add_message() {
local message=$1
result_json=$(jq --arg message "$message" '.messages += [$message]' <<< "$result_json")
}
# Install an ogLive client from a previously downloaded ISO image.
function install() {
local OGLIVEFILE OGLIVEDIST OGLIVEREV OGLIVEKRNL OGLIVEDIR OGINITRD OGSQFS OGCLIENT=ogclient
local COMPRESS SAMBAPASS TMPDIR RSYNCSERV RSYNCCLNT JSON_OUTPUT
[ $# -ne 1 ] && { echo "{\"status\": \"error\", \"error\": \"usage\"}"; exit 1; }
OGLIVEFILE=$(realpath $DOWNLOADDIR/$1)
[ $(echo $OGLIVEFILE | wc -w) -gt 1 ] && { echo "{\"status\": \"error\", \"error\": \"usage\"}"; exit 1; }
[ ! -f $OGLIVEFILE ] && { echo "{\"status\": \"error\", \"error\": \"not found $1.\"}"; exit 1; }
[ ! -r $OGLIVEFILE ] && { echo "{\"status\": \"error\", \"error\": \"access $1.\"}"; exit 1; }
[ ! -w $(dirname $INFOFILE) ] && { echo "{\"status\": \"error\", \"error\": \"access configuration directory.\"}"; exit 1; }
[ ! -w $TFTPDIR ] && { echo "{\"status\": \"error\", \"error\": \"access installation directory.\"}"; exit 1; }
[ -z "$(file -b $OGLIVEFILE | grep "ISO.*ogClient")" ] && { echo "{\"status\": \"error\", \"error\": \"File is not an ogLive ISO image.\"}"; exit 1; }
OGLIVEDIST="$(echo $OGLIVEFILE|cut -f2 -d-)"
OGLIVEREV="${OGLIVEFILE##*-}"; OGLIVEREV="${OGLIVEREV%%.*}"
OGLIVEKRNL="$(echo $OGLIVEFILE|cut -f3- -d-)"; OGLIVEKRNL="${OGLIVEKRNL%-$OGLIVEREV.*}"
OGLIVEARCH="$(echo $OGLIVEFILE|awk -F- '{print $(NF-1)}')"
case "$OGLIVEARCH" in
i386|amd64)
OGLIVEKRNL="${OGLIVEKRNL%-$OGLIVEARCH}" ;;
*)
OGLIVEARCH="i386" ;;
esac
OGLIVEDIR="$TFTPDIR/$DEFOGLIVE-${OGLIVEKRNL%%-*}-$OGLIVEARCH-$OGLIVEREV"
OGLIVEDIR="${OGLIVEDIR/amd64-/}"
OGINITRD=$OGLIVEDIR/oginitrd.img
[ ! -r $OGINITRD ] && OGINITRD=$TFTPDIR/$DEFOGLIVE/oginitrd.img
if [ -r $OGINITRD ]; then
COMPRESS=$(file -b "$OGINITRD" | awk '{print tolower($1);}')
SAMBAPASS=$($COMPRESS -dc $OGINITRD | \
cpio -i --to-stdout scripts/ogfunctions 2>/dev/null | \
sed -n '/^[ \t].*OPTIONS=/s/.*pass=\(\w*\).*/\1/p')
fi
rm -fr ${OGLIVEDIR}.old
mv -f $OGLIVEDIR ${OGLIVEDIR}.old 2>/dev/null
TMPDIR=/tmp/${OGLIVEFILE%.iso}
mkdir -p $OGLIVEDIR $TMPDIR
trap "umount $TMPDIR; rm -fr $TMPDIR" 1 2 3 6 9 15
mount -o loop,ro $OGLIVEFILE $TMPDIR >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"mount failed.\"}"; exit 1; }
cp -va $TMPDIR/ogclient/* $OGLIVEDIR >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"Cannot copy files to ogLive directory.\"}"; exit 1; }
umount $TMPDIR >/dev/null 2>&1
if [ ! -f $INFOFILE ]; then
rm -f $TFTPDIR/$DEFOGLIVE $TFTPDIR/$OGCLIENT
ln -vfs $(basename $OGLIVEDIR) $TFTPDIR/$DEFOGLIVE >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"Linking to $TFTPDIR/$DEFOGLIVE failed.\"}"; exit 1; }
ln -vfs $DEFOGLIVE $TFTPDIR/$OGCLIENT >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"Linking to $TFTPDIR/$OGCLIENT failed.\"}"; exit 1; }
fi
if [ -n "$SAMBAPASS" ]; then
echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"setsmbpass failed.\"}"; exit 1; }
else
$OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"setsmbpass failed.\"}"; exit 1; }
fi
find -L $OGLIVEDIR -type d -exec chmod 755 {} \; >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"chmod directories failed.\"}"; exit 1; }
find -L $OGLIVEDIR -type f -exec chmod 644 {} \; >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"chmod files failed.\"}"; exit 1; }
chown -R :opengnsys $OGLIVEDIR >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"chown failed.\"}"; exit 1; }
OGSQFS=$OGLIVEDIR/ogclient.sqfs
if mount -o loop,ro $OGSQFS $TMPDIR >/dev/null 2>&1; then
RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}')
RSYNCCLNT=$(chroot $TMPDIR /usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')
if [ -z "$RSYNCSERV" ] || [ "$RSYNCSERV" -gt "${RSYNCCLNT:-1}" ]; then
if [ -e "$OPENGNSYS/client/bin/rsync-$RSYNCSERV" ]; then
mv -f "$OPENGNSYS/client/bin/rsync-$RSYNCSERV" "$OPENGNSYS/client/bin/rsync" 2>/dev/null
fi
else
if [ -e "$OPENGNSYS/client/bin/rsync" ]; then
mv -f "$OPENGNSYS/client/bin/rsync" "$OPENGNSYS/client/bin/rsync-$($OPENGNSYS/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')"
fi
fi
umount $TMPDIR >/dev/null 2>&1
rmdir $TMPDIR >/dev/null 2>&1 || rm -rf $TMPDIR >/dev/null 2>&1
fi
# Crear JSON output
JSON_OUTPUT=$(jq -n \
--arg dist "$OGLIVEDIST" \
--arg krnl "$OGLIVEKRNL" \
--arg arch "$OGLIVEARCH" \
--arg rev "$OGLIVEREV" \
--arg dir "$OGLIVEDIR" \
--arg iso "$(basename "$OGLIVEFILE")" \
'{status: "success", messages: [], result: {distribution: $dist, kernel: $krnl, architecture: $arch, revision: $rev, directory: $dir, iso: $iso}}')
echo "$JSON_OUTPUT"
}
# Uninstall an ogLive client.
function uninstall() {
local CHECKSUM DIR
# Validar que se proporcionó exactamente un argumento (el checksum)
[ $# -ne 1 ] && { echo "{\"error\": \"usage: uninstall {checksum}\"}"; exit 1; }
CHECKSUM=$1
# Verificar acceso a los directorios necesarios
[ ! -w $TFTPDIR ] && { echo "{\"error\": \"access installation directory.\"}"; exit 1; }
# Buscar el directorio correspondiente al checksum
DIR=$(find $TFTPDIR -type f -name 'ogclient.sqfs.sum' -exec grep -l "$CHECKSUM" {} \; | xargs -I{} dirname {})
# Si no se encuentra el directorio, devolver error
if [ -z "$DIR" ]; then
echo "{\"error\": \"ogLive client with checksum $CHECKSUM not found.\"}"
exit 1
fi
# Eliminar archivos y directorio, redirigiendo la salida a /dev/null
rm -vfr $DIR > /dev/null 2>&1
# Comprobar si la eliminación tuvo éxito
if [ -d "$DIR" ]; then
echo "{\"error\": \"Failed to uninstall ogLive client in $DIR.\"}"
exit 1
fi
# Devolver mensaje de éxito
echo "{\"message\": \"ogLive client uninstalled successfully.\", \"details\": \"Removed directory: $DIR\"}"
}
# Get information about the default ogLive client.
function get_default() {
local DEFAULT_LINK="$TFTPDIR/$DEFOGLIVE"
local DIR OGLIVEDIST OGLIVEKRNL OGLIVEARCH OGLIVEREV OGLIVEISO OGLIVEDIR
# Verificar que el enlace simbólico del ogLive por defecto existe.
if [ ! -L "$DEFAULT_LINK" ]; then
echo "{\"error\": \"Default ogLive client link not found.\"}"
exit 1
fi
# Obtener el directorio real al que apunta el enlace simbólico.
DIR=$(readlink -f "$DEFAULT_LINK")
# Si no se encuentra el directorio, devolver error.
if [ -z "$DIR" ]; then
echo "{\"error\": \"Default ogLive client directory not found.\"}"
exit 1
fi
# Obtener la información del ogLive a partir del nombre del directorio.
OGLIVEDIR=$(basename "$DIR")
OGLIVEDIST="$(echo $OGLIVEDIR | cut -d- -f2)"
OGLIVEKRNL="$(echo $OGLIVEDIR | cut -d- -f3)"
OGLIVEARCH="amd64" # Suponiendo que siempre es amd64
OGLIVEREV="$(echo $OGLIVEDIR | cut -d- -f4)"
OGLIVEISO="" # No tenemos la información del ISO aquí, podría necesitarse un ajuste si se requiere
# Construir el JSON con la información.
local INFO=$(cat << EOT
{
"distribution": "$OGLIVEDIST",
"kernel": "$OGLIVEKRNL",
"architecture": "$OGLIVEARCH",
"revision": "$OGLIVEREV",
"directory": "$DIR",
"iso": "$OGLIVEISO"
}
EOT
)
# Devolver la información en formato JSON.
echo "$INFO"
}
# Set default ogLive client by checksum.
function set_default() {
local CHECKSUM=$1
local DIR
# Validar que se proporcionó exactamente un argumento (el checksum)
[ $# -ne 1 ] && { echo "{\"error\": \"usage: set-default {checksum}\"}"; exit 1; }
# Verificar acceso a los directorios necesarios
[ ! -w $TFTPDIR ] && { echo "{\"error\": \"access installation directory.\"}"; exit 1; }
# Buscar el directorio correspondiente al checksum
DIR=$(find $TFTPDIR -type f -name 'ogclient.sqfs.sum' -exec grep -l "$CHECKSUM" {} \; | xargs -I{} dirname {} | grep -v ".old")
# Si no se encuentra el directorio, devolver error
if [ -z "$DIR" ]; then
echo "{\"error\": \"ogLive client with checksum $CHECKSUM not found.\"}"
exit 1
fi
# Eliminar el enlace simbólico existente y crear uno nuevo
rm -f $TFTPDIR/$DEFOGLIVE > /dev/null 2>&1
ln -vfs $(basename $DIR) $TFTPDIR/$DEFOGLIVE > /dev/null 2>&1
# Comprobar si el enlace simbólico se creó correctamente
if [ "$(readlink -f $TFTPDIR/$DEFOGLIVE)" == "$(readlink -f $DIR)" ]; then
echo "{\"message\": \"ogLive client set as default successfully.\", \"details\": \"$DIR\"}"
else
echo "{\"error\": \"Failed to set default ogLive client.\"}"
exit 1
fi
}
# Rebuild a lost configuration file.
function rebuild() {
local i INST NF DEF
[ $# -ne 0 ] && raiseError usage
[ -f $INFOFILE ] && raiseError access "Configuration file exists."
INST=$(find $TFTPDIR/ -type d -name "$DEFOGLIVE-*" -a ! -name "*.old" -printf "%f\n" | sort)
for i in $INST; do
NF=$(echo $i | awk -F- '{print NF-1}')
case $NF in
1) addToJson "" "$(echo $i|cut -f2 -d-)" "i386" "" "$i" "" ;;
2) eval addToJson $(echo $i | awk -F- '{printf "\"\" %s amd64 %s %s \"\"",$2,$3,$0}') ;;
3) eval addToJson $(echo $i | awk -F- '{if ($3=="i386") printf "\"\" %s %s %s %s \"\"",$2,$3,$4,$0; else printf "%s %s i386 %s %s \"\"",$2,$3,$4,$0}') ;;
4) eval addToJson $(echo $i | awk -F- '{printf "%s %s %s %s %s \"\"",$2,$3,$4,$5,$0}') ;;
esac
# Check for is default oglive.
[ -n "$(stat -c "%N" $TFTPDIR/$DEFOGLIVE | awk '$3~/'$i'/ {print}')" ] && DEF="$i"
done
# Set default ogLive.
[ -n "$DEF" ] && setdefault $(search $DEF)
}
# Assign an ISO file to a JSON entry.
function assign() {
local ISOFILE DIR
[ $# -ne 2 ] && raiseError usage
[ ! -w $INFOFILE ] && raiseError access "Configuration file."
# Check if ISO file and index directory exist.
ISOFILE=$DOWNLOADFILE/$1
[ ! -f $DOWNLOADDIR/$ISOFILE ] && raiseError notfound "ISO file \"$1\"."
DIR=$(search $2 2>/dev/null)
[ ! -d $TFTPDIR/$DIR ] && raiseError notfound "Directory for index \"$2\"."
# Assign ISO file to JSON entry.
jq ".oglive[$2].iso=\"$1\"" $INFOFILE | sponge $INFOFILE && jq ".oglive[$2]" $INFOFILE
}
# Get disk usage information
function disk_usage() {
DISK_INFO=$(df -h / | awk 'NR==2{print "{\"total\":\""$2"\", \"used\":\""$3"\", \"available\":\""$4"\", \"percentage\":\""$5"\"}"}')
echo $DISK_INFO
}
# Function to list installed ogLive clients and the default ogLive client
function list_installed_oglives() {
local INST NF DEF
INST=$(find $TFTPDIR/ -type d -name "$DEFOGLIVE-*" -a ! -name "*.old" -printf "%f\n" | sort)
local installed_ogLives=()
for i in $INST; do
NF=$(echo $i | awk -F- '{print NF-1}')
local OGLIVEDIST=""
local OGLIVEKRNL=""
local OGLIVEARCH=""
local OGLIVEREV=""
local CHECKSUM=""
local CHECKSUM_FILE="$TFTPDIR/$i/ogclient.sqfs.sum"
if [ -f "$CHECKSUM_FILE" ]; then
CHECKSUM=$(cat "$CHECKSUM_FILE" | cut -d ' ' -f 1)
fi
case $NF in
1) OGLIVEDIST="" OGLIVEKRNL=$(echo $i|cut -f2 -d-) OGLIVEARCH="i386" OGLIVEREV="" ;;
2) eval $(echo $i | awk -F- '{printf "OGLIVEDIST=\"\" OGLIVEKRNL=%s OGLIVEARCH=amd64 OGLIVEREV=%s OGLIVEDIR=%s",$2,$3,$0}') ;;
3) eval $(echo $i | awk -F- '{if ($3=="i386") printf "OGLIVEDIST=\"\" OGLIVEKRNL=%s OGLIVEARCH=%s OGLIVEREV=%s OGLIVEDIR=%s",$2,$3,$4,$0; else printf "OGLIVEDIST=%s OGLIVEKRNL=%s OGLIVEARCH=i386 OGLIVEREV=%s OGLIVEDIR=%s",$2,$3,$4,$0}') ;;
4) eval $(echo $i | awk -F- '{printf "OGLIVEDIST=%s OGLIVEKRNL=%s OGLIVEARCH=%s OGLIVEREV=%s OGLIVEDIR=%s",$2,$3,$4,$5,$0}') ;;
esac
local DATA=$(jq -n \
--arg id "$CHECKSUM" \
--arg dist "$OGLIVEDIST" \
--arg krnl "$OGLIVEKRNL" \
--arg arch "$OGLIVEARCH" \
--arg rev "$OGLIVEREV" \
--arg dir "$TFTPDIR/$OGLIVEDIR" \
--arg iso "" \
'{id: $id, distribution: $dist, kernel: $krnl, architecture: $arch, revision: $rev, directory: $dir, iso: $iso}')
installed_ogLives+=("$DATA")
[ -n "$(stat -c "%N" $TFTPDIR/$DEFOGLIVE | awk '$3~/'$i'/ {print}')" ] && DEF="$i"
done
local default_oglive=$(basename $(readlink -f $TFTPDIR/$DEFOGLIVE))
jq -n \
--arg default_oglive "$default_oglive" \
--argjson installed_ogLives "$(printf '%s\n' "${installed_ogLives[@]}" | jq -s .)" \
'{
default_oglive: $default_oglive,
installed_ogLives: $installed_ogLives
}'
}
# Get information about an installed ogLive client.
function get_info() {
local CHECKSUM="$1"
local DIR OGLIVEDIST OGLIVEKRNL OGLIVEARCH OGLIVEREV OGLIVEISO OGLIVEDIR
# Verificar que se proporcionó un checksum.
[ -z "$CHECKSUM" ] && { echo "{\"error\": \"usage: get_info {checksum}\"}"; exit 1; }
# Verificar acceso al directorio de instalación.
[ ! -w $TFTPDIR ] && { echo "{\"error\": \"access installation directory.\"}"; exit 1; }
# Buscar el directorio correspondiente al checksum, excluyendo los que terminan en .old.
DIR=$(find $TFTPDIR -type f -name 'ogclient.sqfs.sum' -exec grep -l "$CHECKSUM" {} \; | grep -v '.old' | xargs -I{} dirname {})
# Si no se encuentra el directorio, devolver error.
if [ -z "$DIR" ]; then
echo "{\"error\": \"ogLive client with checksum $CHECKSUM not found.\"}"
exit 1
fi
# Obtener la información del ogLive a partir del nombre del directorio.
OGLIVEDIR=$(basename "$DIR")
OGLIVEDIST="$(echo $OGLIVEDIR | cut -d- -f2)"
OGLIVEKRNL="$(echo $OGLIVEDIR | cut -d- -f3)"
OGLIVEARCH="amd64" # Suponiendo que siempre es amd64
OGLIVEREV="$(echo $OGLIVEDIR | cut -d- -f4)"
OGLIVEISO="" # No tenemos la información del ISO aquí, podría necesitarse un ajuste si se requiere
# Construir el JSON con la información.
local INFO=$(cat << EOT
{
"distribution": "$OGLIVEDIST",
"kernel": "$OGLIVEKRNL",
"architecture": "$OGLIVEARCH",
"revision": "$OGLIVEREV",
"directory": "$DIR",
"iso": "$OGLIVEISO"
}
EOT
)
# Devolver la información en formato JSON.
echo "$INFO"
}
# Function to check the status of services
function check_services_status() {
local SERVICES=("oglive_daemon.service" "tftpd-hpa.service" "nginx.service")
declare -A STATUS_MAP
for service in "${SERVICES[@]}"; do
if systemctl list-units --type=service --all | grep -q "$service"; then
STATUS=$(systemctl is-active "$service")
STATUS_MAP[$service]=$STATUS
else
STATUS_MAP[$service]="not installed"
fi
done
local json_output=$(jq -n \
--arg oglive_daemon "${STATUS_MAP['oglive_daemon.service']}" \
--arg tftpboot "${STATUS_MAP['tftpd-hpa.service']}" \
--arg nginx "${STATUS_MAP['nginx.service']}" \
'{
oglive_daemon: $oglive_daemon,
tftpboot: $tftpboot,
nginx: $nginx
}')
echo "$json_output"
}
# Main progrram.
# Access control.
[ -r $OPENGNSYS/www/controlacceso.php ] && ACCESS="web"
[ "$USER" = "root" ] && ACCESS="root"
[ -z "$ACCESS" ] && raiseError access "Need to be root."
# Check dependencies.
which sponge &>/dev/null || raiseError notfound "Need to install \"moreutils\"."
# Commands control.
shopt -s extglob
case "$ACCESS" in
root) CMDS='+(help|version|convert|config|check|list|show|search|download|install|uninstall|get-default|set-default|rebuild|assign|disk_usage|list_installed_oglives|get_info|get_default|set_default|check_services_status)' ;;
web) CMDS='+(list|show|search|get-default)' ;;
esac
case "$1" in
$CMDS) COMMAND="${1/-/}"; shift; $COMMAND "$@" ;;
*) raiseError usage ;;
esac
exit $?