This commit is contained in:
ai-dev
2025-10-11 12:15:25 +02:00
parent e8681cdead
commit 4957b52f3a
94 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Take down the S6 supervision tree based on service exit code
# ==============================================================================
if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then
bashio::log.warning "avahi crashed, halting add-on"
exec /run/s6/basedir/bin/halt
fi
bashio::log.info "avahi stopped"

View File

@@ -0,0 +1,12 @@
#!/usr/bin/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Start avahi service
# ==============================================================================
declare SMB_HOST
SMB_HOST=$(grep -i '^\s*netbios name\s*=' /etc/samba/smb.conf | cut -f2 -d= | tr -d '[:blank:]')
bashio::log.info "Starting the AVAHI for ${SMB_HOST%.*}..."
exec avahi-publish-service -v -f -s "${SMB_HOST%.*}" _smb._tcp 445

View File

@@ -0,0 +1 @@
longrun

View File

@@ -0,0 +1 @@
/etc/s6-overlay/s6-rc.d/cifs-supervisor-mount/finish

View File

@@ -0,0 +1,17 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Take down the S6 supervision tree based on service exit code
# ==============================================================================
if [ -f /tmp/cifs_network ]; then
bashio::log.info "Umount Network Automount Shares..."
available_shares=$(awk '/\[(.*)\]/{ DISK=substr($1,2,length($1)-2); next } /.*path =(.*)/{ printf "%s\n",DISK,$0 }' /etc/samba/smb.conf)
while read -r -a device; do
[[ "share config addons ssl backup media all_addon_configs homeassistant" =~ ${device,,} ]] && continue
status=$(bashio::api.supervisor DELETE /mounts/${device})
bashio::log.info "Return from Umount ${status}"
done <<<"${available_shares}"
fi

View File

@@ -0,0 +1,57 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Amoutomount Shares with new system!
# ==============================================================================
if [ -f /tmp/cifs_network ]; then
#bashio::log.level all
bashio::log.info "Automount Shares..."
ipaddress=$(bashio::addon.ip_address)
#username=$(bashio::config 'username')
#password=$(bashio::config 'password')
username=$(jq -r '.username' </tmp/auth.json)
password=$(jq -r '.password' </tmp/auth.json)
available_shares=$(awk '/\[(.*)\]/{ DISK=substr($1,2,length($1)-2); next } /.*path =(.*)/{ printf "%s\n",DISK,$0 }' /etc/samba/smb.conf)
#info=$(bashio::api.supervisor GET /host/info false)
#bashio::log "Info: ${info}"
#mounts=$(bashio::api.supervisor GET /mounts false)
#bashio::log "Mounts: ${mounts}"
#status=$(smbcontrol smbd ping)
#bashio::log "Samba Ready: ${status}"
#bashio::log "Children: $(smbcontrol smbd num-children)"
bashio::log.info "Wait Samba Server to going up..(max 60s)"
# timeout 30 bash -c 'until printf "" 2>>/dev/null >>/dev/tcp/$0/$1; do sleep 1; done' ${ipaddress/\/*/} 445
bashio::net.wait_for 445 ${ipaddress/\/*/} 60
# smbstatus
while read -r -a device; do
[[ ${device,,} == @(share|config|addons|ssl|backup|media|addon_configs|homeassistant) ]] && continue
usage=$(jq -r --arg xshare "$device" '.acl[] | select(.share==$xshare) | .usage // "media"' <<<"$(bashio::addon.config)")
cmdshare=$(jq -nrc --arg usage "${usage:-media}" --arg share "$device" --arg ip "${ipaddress/\/*/}" --arg user "$username" --arg pwd "$password" '.name=$share|.usage=$usage|.type="cifs"|.server=$ip|.share=$share|.username=$user|.password=$pwd')
#bashio::log.info $(jq '.password="********"' <<<${cmdshare})
#bashio::log.info $(bashio::api.supervisor GET /mounts)
#bashio::log.info $(bashio::api.supervisor GET /mounts | jq -r --arg xshare "$device" '.mounts[] | select(.name == $xshare ) // empty')
if [[ ! -z $(bashio::api.supervisor GET /mounts | jq -r --arg xshare "$device" '.mounts[] | select(.name == $xshare ) // empty') ]]; then
bashio::log.info "Share Already Found ${device} - Remove!"
bashio::api.supervisor DELETE /mounts/${device} || true
fi
for rt in {1..3}; do
status=$(bashio::api.supervisor POST /mounts "${cmdshare}") && break
bashio::log.warning "Retry ${rt}/3 Error Automount ${device} Msg: $(jq -c '.password="********"' <<<${cmdshare})"
sleep 3
done
done <<<"${available_shares}"
fi

View File

@@ -0,0 +1 @@
oneshot

View File

@@ -0,0 +1 @@
/etc/s6-overlay/s6-rc.d/cifs-supervisor-mount/run

View File

@@ -0,0 +1,10 @@
#!/usr/bin/with-contenv bashio
# ==============================================================================
# Take down the S6 supervision tree based on service exit code
# ==============================================================================
if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then
bashio::log.warning "hd-idle crashed, halting add-on"
exec /run/s6/basedir/bin/halt
fi
bashio::log.info "hd-idle stopped"

View File

@@ -0,0 +1,13 @@
#!/usr/bin/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Start hd-idle service
# ==============================================================================
if bashio::config.has_value 'hdd_idle_seconds' && ! bashio::config.equals 'hdd_idle_seconds' '0'; then
bashio::log.info "Enabling HDD IDLE after $(bashio::config 'hdd_idle_seconds')sec"
bashio::log.warning "HDD IDLE is subject to host file-handle policy. So severals minutes can be wait before real IDLE can be performed!"
mkfifo /tmp/hdidle.events || true
exec hd-idle -i "$(bashio::config 'hdd_idle_seconds')" | tee /tmp/hdidle.events
else
exec sleep infinity
fi

View File

@@ -0,0 +1 @@
longrun

View File

@@ -0,0 +1 @@
/etc/s6-overlay/s6-rc.d/init-automount/finish

View File

@@ -0,0 +1,27 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Umount all drivers.
# ==============================================================================
declare interface
declare ipaddress
interface=$(bashio::network.name)
ipaddress=$(bashio::network.ipv4_address ${interface})
if [[ -f /tmp/local_mount ]]; then
readarray -t umdev </tmp/local_mount
if [ ${#umdev[@]} -gt 0 ]; then
bashio::log.info "Unmount drivers:\n$(printf "%s\n" "${umdev[@]}")"
umount "${umdev[@]}" 2>/dev/null || true
fi
fi
if [[ -f /tmp/remote_mount ]]; then
readarray -t umdev </tmp/remote_mount
if [ ${#umdev[@]} -gt 0 ]; then
bashio::log.info "Unmount Host drivers:\n$(printf "%s\n" "${umdev[@]}")"
line=$(printf "\"%s\" " "${umdev[@]}")
ssh root@${ipaddress%/*} -p 22222 -o "StrictHostKeyChecking no" "umount $line" || true
fi
fi
bashio::log.info "Bye."

View File

@@ -0,0 +1,313 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Mounting external HD and modify the smb.conf
# ==============================================================================
declare moredisks
declare autodisks
declare tomountdisks
declare interface
declare ipaddress
declare ssh_private_key
declare remote_mount
declare network_mount
declare fstypes
declare dev
declare mntops
declare reserved_names
function disk2label() { # $1 disk return (label disk or id)
local disk=$1
if [[ $disk == id:* ]]; then
disk=${disk:3}
if [ -L /dev/disk/by-id/"$disk" ]; then
label=$(lsblk -no label /dev/disk/by-id/"$disk")
# fstype=$(lsblk -no fstype /dev/disk/by-id/"$disk")
if [[ -n "$label" && -L "/dev/disk/by-label/$label" ]]; then
bashio::log.info "Disk with id ${disk} is labeled $label so $label is used."
disk="$label"
# elif [[ $fstype == apfs ]]; then
# disk=$(apfsutil /dev/disk/by-id/"$disk" | awk -F "[, ]+" '/Name:/{print $2}')
else
disk=$1
fi
else
bashio::log.warning "Disk with id ${disk} not found."
return 1
fi
else
blkid -L "$disk" >>/dev/null || {
bashio::log.warning "Disk with label ${disk} not found."
return 1
}
fi
echo "$disk"
return 0
}
# Check for reserved mount name
function reserved_mount_name() { # $1 disk
disk=$1
reserved_names=(config addons ssl share backup media all_addon_configs homeassistant)
# Clean reserved name with disaled
for rdisk in "${reserved_names[@]}"; do
deleted=$(jq -r --arg share "${rdisk,,}" '.acl[] | select( (.share|ascii_upcase) == ($share|ascii_upcase) ) | select (.disabled) | .share' </data/options.json)
reserved_names=("${reserved_names[@]/$deleted/}")
done
# Clean tomountdisks
for rdisk in "${reserved_names[@]}"; do
if [[ ${rdisk,,} = ${disk,,} ]]; then
tomountdisks=("${tomountdisks[@]/$disk/}")
return 0
fi
done
}
# mount a disk from parameters
function mount_disk() { # $1 disk $2 path $3 remote_mount $4 mount_options
disk=$1
path=$2
remote_mount=$3
mntops=$4
if [[ $disk == id:* ]]; then
bashio::log.debug "Disk ${disk:3} is an ID"
if [ -L "/dev/disk/by-uuid/${disk:3}" ]; then
dev=/dev/disk/by-uuid/${disk:3}
disk=${disk:3}
elif [ -L "/dev/disk/by-id/${disk:3}" ]; then
dev=/dev/disk/by-id/${disk:3}
disk=${disk:3}
elif [ -L "/dev/disk/by-partuuid/${disk:3}" ]; then
dev=/dev/disk/by-partuuid/${disk:3}
disk=${disk:3}
else
unset dev
fi
else
dev=$(blkid -L "$disk")
fi
if [ ! ${dev:+1} ]; then
bashio::log.info "Disk ${disk} not found! <SKIP>"
return 0
fi
mdisk=$(printf %b "$disk")
mkdir -p "$path/$mdisk"
chmod a+rwx "$path/$mdisk"
# check with findmnt if the disk is already mounted
if findmnt -n -o TARGET "$path/$mdisk" >/dev/null 2>&1; then
bashio::log.info "Disk ${mdisk} is already mounted"
echo "$path"/"$mdisk" >>/tmp/local_mount
return 0
else
# Check FS type and set relative options
fstype=$(lsblk "$dev" -no fstype)
options="${mntops}"
type="auto"
cmd="mount"
case "$fstype" in
exfat | vfat | msdos)
bashio::log.warning "Your ${mdisk} is ${fstype}. Permissions and ACL don't works and this is an EXPERIMENTAL support"
options="${options},umask=000"
;;
ntfs)
bashio::log.warning "Your ${mdisk} is ${fstype}. This is an EXPERIMENTAL support"
options="${options},umask=000"
type="ntfs3"
;;
apfs)
bashio::log.warning "Your ${mdisk} is ${fstype}. This is an EXPERIMENTAL support and work only in RO. Mount options not supported!"
type=""
options=""
cmd="mount.apfs"
;;
esac
# Create mount arg array
m_args=()
if [ -n "$type" ]; then
m_args+=("-t" $type)
fi
if [ -n "$options" ]; then
m_args+=("-o" $options)
fi
m_args+=("${dev}")
bashio::log.debug "Mounting ${mdisk} of type ${fstype} with ${m_args[@]}"
if [ "$remote_mount" = true ]; then
ssh root@"${ipaddress%/*}" -p 22222 -o "StrictHostKeyChecking no" "if findmnt '/mnt/data/supervisor/media/$mdisk ' >/dev/null; then echo 'Disk $mdisk already mounted on host' ; else $cmd ${m_args[@]} '/mnt/data/supervisor/media/$mdisk'; fi" &&
echo "$dev" >>/tmp/remote_mount
fi || bashio::log.warning "Host Mount ${mdisk}[${fstype}] Fail!" || :
bashio::log.debug "Exec command: ${cmd} ${m_args[@]} \"${path}/${mdisk}\""
$cmd ${m_args[@]} "$path/$mdisk" &&
echo "$path"/"$mdisk" >>/tmp/local_mount &&
jq --arg dname "${mdisk}" --arg path "${path}/${mdisk}" --arg fs "${fstype}" ' . += {($dname | gsub( "-"; "_") | ascii_upcase ):{"path":$path,"fs":$fs}}' /tmp/local_mount.json >/tmp/local_mount.json.tmp &&
mv /tmp/local_mount.json.tmp /tmp/local_mount.json &&
bashio::log.info "Mount ${mdisk}[${fstype}] Success!"
fi
}
# Error for Operating System
if ! [[ "$(bashio::info.operating_system)" =~ ^Home\ Assistant\ OS.* ]]; then
bashio::log.warning "Your operating system $(bashio::info.operating_system) is not supported! "
bashio::log.red "+------------------------------------------------------------------+"
bashio::log.red "| THIS ADDON IS DESIGNED FOR HOME ASSISTANT OPERATING SYSTEM ONLY! |"
bashio::log.red "| THIS ADDON IS DESIGNED FOR HOME ASSISTANT OPERATING SYSTEM ONLY! |"
bashio::log.red "| THIS ADDON IS DESIGNED FOR HOME ASSISTANT OPERATING SYSTEM ONLY! |"
bashio::log.red "| THIS ADDON IS DESIGNED FOR HOME ASSISTANT OPERATING SYSTEM ONLY! |"
bashio::log.red "| THIS ADDON IS DESIGNED FOR HOME ASSISTANT OPERATING SYSTEM ONLY! |"
bashio::log.red "+------------------------------------------------------------------+"
if bashio::config.exists 'meaning_of_life' && [[ $(bashio::config 'meaning_of_life') -eq 42 ]]; then
bashio::log.green "Deep Thought permission accepted!"
else
bashio::exit.nok "You can force this addon to run only if you known the meaning of life!"
fi
fi
# Mount external drive
bashio::log.info "Protection Mode is $(bashio::addon.protected)"
# shellcheck disable=SC2091
if $(bashio::addon.protected) && (bashio::config.has_value 'moredisks' || bashio::config.true 'automount'); then
bashio::log.warning "MoreDisk and Automount ignored because ADDON in Protected Mode!"
bashio::config.suggest "protected" "moredisk only work when Protection mode is disabled"
elif bashio::config.has_value 'moredisks' || bashio::config.true 'automount'; then
bashio::log.info "MoreDisk or Automount option found!"
# Check supported FS
for mfs in ntfs3 exfat btrfs xfs; do
modprobe $mfs || bashio::log.warning "$mfs module not available!"
done
fstypes=$(grep -v nodev </proc/filesystems | tr -d '\n')
bashio::log.blue "---------------------------------------------------"
bashio::log.green "Supported fs: ${fstypes}"
if grep -q fuseblk </proc/filesystems; then bashio::log.green "Supported fusefs: $(find /usr/sbin -name "mount*" | cut -c 17- | tr "\n" " " | sed s/fuse.//g)"; fi
bashio::log.blue "---------------------------------------------------"
# Check Host Ssh config
remote_mount=false
network_mount=false
path=/mnt
if bashio::config.true 'medialibrary.enable'; then
bashio::log.info "MediaLibrary option found!"
if bashio::config.is_empty 'medialibrary.ssh_private_key'; then
# Check OS Capability
features=$(bashio::info 'supervisor.info.features' '.features')
#bashio::log "Features ${features}"
if grep \"mount\" <<<"${features}" >/dev/null; then
touch "/tmp/cifs_network"
else
bashio::log.warning "Unsupported Mount Feature by system!"
bashio::config.suggest "ssh_private_key" "Your host system don't upport mount feature\nSSH Private Key is required for enable medialibrary deprected feature."
fi
else
bashio::log.red "+-------------------------------------------------------------------------------------+"
bashio::log.warning "|SSH Private Key *DEPRECATED WARNING* The use of old experimental system is deprecated|"
bashio::log.warning "|Remove the key and try the new system to mound /media and /share data disks |"
bashio::log.red "+-------------------------------------------------------------------------------------+"
interface=$(bashio::network.name)
ipaddress=$(bashio::network.ipv4_address "${interface}")
ssh_private_key=$(bashio::config 'medialibrary.ssh_private_key')
mkdir -p /root/.ssh
echo "${ssh_private_key}" >/root/.ssh/id_rsa
chmod ag-rw /root/.ssh/id_rsa
if ssh root@"${ipaddress%/*}" -p 22222 -o "StrictHostKeyChecking no" "date"; then
bashio::log.info "SSH connection to ${ipaddress%/*}:22222 OK"
remote_mount=true
path=/media
else
bashio::log.warning "SSH connection to ${ipaddress%/*}:22222 FAILED"
bashio::log.warning "MediaLibrary disabled due error in config!"
fi
fi
else
bashio::log.info "MediaLibrary disabled in config. Disk are mounted only for this addon!"
fi
OIFS=$IFS
IFS=$'\n'
## List available Disk with Labels and Id
if bashio::config.true 'available_disks_log' || bashio::config.true 'automount'; then
bashio::log.blue "---------------------------------------------------"
#readarray -t autodisks < <(lsblk -E label -n -o label -i | sed -r '/^\s*$/d' | grep -v hassos)
readarray -t autodisks < <(/usr/bin/poetry -C /usr/local/bin/ run python /usr/local/bin/disklist.py)
if [ ${#autodisks[@]} -eq 0 ]; then
bashio::log.info "No Disk with labels."
else
bashio::log.info "Available Disk Labels:"
for disk in "${autodisks[@]}"; do
if [[ $disk == id:* ]]; then
bashio::log.info "\t${disk}[$(lsblk $(blkid -U "${disk:3}") -no fstype)]"
else
bashio::log.info "\t${disk}[$(lsblk $(blkid -L "$disk") -no fstype)]"
fi
done
fi
bashio::log.blue "---------------------------------------------------"
fi
mnt_ops=($(bashio::config 'mountoptions'))
mnt_ops=$(
IFS=,
echo "${mnt_ops[*]}"
)
moredisks=($(bashio::config 'moredisks'))
if [ ${#moredisks[@]} -eq 0 ]; then
bashio::log.info "No MoreDisks to mount"
else
bashio::log.info "MoreDisks to mount:\n" $(printf "\t%s\n" "${moredisks[@]}")
i=0
mmoredisks=()
for index in "${!moredisks[@]}"; do
tmpd=$(disk2label "${moredisks[$index]}") &&
mmoredisks[$i]=$tmpd &&
((i = i + 1))
done
moredisks=("${mmoredisks[@]}")
fi
if bashio::config.true 'automount' && [ ${#autodisks[@]} -gt 0 ]; then
bashio::log.info "Automount is Enabled!"
tomountdisks=("${autodisks[@]}" "${moredisks[@]}")
tomountdisks=($(sort -u <<<"${tomountdisks[*]}"))
else
tomountdisks=("${moredisks[@]}")
fi
if [ ${#tomountdisks[@]} -gt 0 ]; then
bashio::log.magenta "---------------------------------------------------"
bashio::log.info "Checking Mounting disks for reserved names:\n" $(printf "\t%s\n" "${tomountdisks[@]}")
bashio::log.magenta "---------------------------------------------------"
for disk in "${tomountdisks[@]}"; do
reserved_mount_name "$disk" || bashio::log.warning "Fail to mount ${disk} due to reserved name!"
done
fi
echo "{}" >/tmp/local_mount.json
if [ ${#tomountdisks[@]} -gt 0 ]; then
bashio::log.magenta "---------------------------------------------------"
bashio::log.info "Mounting disks:\n" $(printf "\t%s\n" "${tomountdisks[@]}")
bashio::log.magenta "---------------------------------------------------"
for disk in "${tomountdisks[@]}"; do
mount_disk "$disk" "$path" "$remote_mount" "$mnt_ops" || bashio::log.warning "Fail to mount ${disk} ${mnt_ops} !"
done
fi
IFS=$OIFS
echo "$path" >/tmp/mountpath
fi

View File

@@ -0,0 +1 @@
oneshot

View File

@@ -0,0 +1 @@
/etc/s6-overlay/s6-rc.d/init-automount/run

View File

@@ -0,0 +1,47 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Prepare the MQTT config for running
# ==============================================================================
readonly CONF="/root/.config/mosquitto_pub"
readonly CONF_SUB="/root/.config/mosquitto_sub"
declare host
declare username
declare password
declare port
declare topic
if bashio::config.true "mqtt_enable"; then
topic=$(bashio::config 'mqtt_topic' "sambanas")
host=$(bashio::config 'mqtt_host' "$(bashio::services 'mqtt' 'host')")
username=$(bashio::config 'mqtt_username' "$(bashio::services 'mqtt' 'username')")
password=$(bashio::config 'mqtt_password' "$(bashio::services 'mqtt' 'password')")
port=$(bashio::config 'mqtt_port' "$(bashio::services 'mqtt' 'port')")
topic=$(bashio::config 'mqtt_topic')
#bashio::log.info "Init MQTT config ${host}:${port} ${username}:${password}"
[ -z "$host" ] && bashio::log.warning "No MQTT Server found. Homeassistant integration can't work!"
if bashio::var.has_value "host" && ! bashio::config.false "mqtt_enable" && [ -n "$host" ]; then
{
echo "-h ${host}"
echo "--username ${username}"
echo "--pw ${password}"
echo "--port ${port}"
} >"${CONF}"
{
echo "-h ${host}"
echo "--username ${username}"
echo "--pw ${password}"
echo "--port ${port}"
} >"${CONF_SUB}"
fi
else
bashio::log.info "MQTT support not enabled in config"
fi

View File

@@ -0,0 +1 @@
oneshot

View File

@@ -0,0 +1 @@
/etc/s6-overlay/s6-rc.d/init-mqtt/run

View File

@@ -0,0 +1,99 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# vim: ft=bash
# ==============================================================================
# Prepare the Samba service for running
# ==============================================================================
declare password
declare username
declare -a interfaces=()
export HOSTNAME
# Check Login data
bashio::config.require 'username'
bashio::config.require 'password'
# Read hostname from API or setting default "hassio"
HOSTNAME=$(bashio::info.hostname)
if bashio::var.is_empty "${HOSTNAME}" || [ "${HOSTNAME}" == "null" ]; then
bashio::log.warning "Can't read hostname, using default."
HOSTNAME="homeassistant"
fi
bashio::log.info "Hostname: ${HOSTNAME}"
if bashio::config.has_value 'interfaces'; then
bashio::log.debug "Interfaces from config: $(bashio::config 'interfaces')"
for interface in $(bashio::config 'interfaces'); do
if [ -d "/sys/class/net/${interface}" ]; then
interfaces+=("${interface}")
else
bashio::log.warning "Interface ${interface} not found, skipping."
fi
done
else
# Get supported interfaces
for interface in $(bashio::network.interfaces); do
interfaces+=("${interface}")
done
fi
if [ ${#interfaces[@]} -eq 0 ]; then
bashio::exit.nok 'No supported interfaces found to bind on.'
fi
bashio::log.info "Interfaces: $(printf '%s ' "${interfaces[@]}")"
bashio::log.info "Docker Interface: $(bashio::network 'network.info.docker.inerface' '.docker.interface') $(bashio::network 'network.info.docker.network' '.docker.address')"
# Generate Samba configuration.
touch /tmp/local_mount
if [[ ! -e /tmp/local_mount.json ]]; then
echo "{}" >/tmp/local_mount.json
fi
jq ".shares = $(jq -c </tmp/local_mount.json) | .interfaces = $(jq -c -n '$ARGS.positional' --args -- "${interfaces[@]}") | .docker_interface = \"$(bashio::network 'network.info.docker.inerface' '.docker.interface')\" | .docker_net = \"$(bashio::network 'network.info.docker.network' '.docker.address')\" | .moredisks = $(jq -R -s -c 'split("\n") | map(select(length > 0)) | [ .[] | ltrimstr("/") ]' </tmp/local_mount) " /data/options.json |
tee /config/bootconfig.json |
tempio \
-template /usr/share/tempio/smb.gtpl \
-out /etc/samba/smb.conf
if [[ "${__BASHIO_LOG_LEVEL_TRACE}" -eq "${__BASHIO_LOG_LEVEL}" ]]; then
bashio::log.info "${__BASHIO_LOG_LEVEL_TRACE} ${__BASHIO_LOG_LEVEL}"
bashio::log.trace "Dump SMB.conf to ADDON_CONFIG/$(hostname) share"
cp /etc/samba/smb.conf /config/smb.conf.dump
fi
function addSambaUser() { # $1 username $2 password
username=$1
password=$2
addgroup "${username}"
adduser -D -H -G "${username}" -s /bin/false "${username}"
(
echo "$password"
echo "$password"
) |
smbpasswd -a -s -c "/etc/samba/smb.conf" "${username}"
}
# Init user
username=$(bashio::config 'username')
password=$(bashio::config 'password')
addSambaUser "${username}" "${password}"
# Init superuser
if [ -f /tmp/cifs_network ]; then
username="_ha_mount_user_"
password=$(sed 's/[-]//g' /proc/sys/kernel/random/uuid | head -c 20)
addSambaUser "${username}" "${password}"
jq -n --arg username "${username}" --arg password "${password}" '{username:$username, password:$password}' >/tmp/auth.json
fi
# Create other users
for user in $(bashio::config 'other_users'); do
username=$(echo "${user}" | jq -r '.username')
password=$(echo "${user}" | jq -r '.password')
addSambaUser "${username}" "${password}"
done
# Log exposed mounted shares
bashio::log.blue "---------------------------------------------------"
bashio::log.info "Exposed Disks Summary:\n$(awk '/\[.*\]$/{ DISK=$0; next } /.*path =(.*)/{ PATH=$0; next} /.*TM:(.*)/{ printf "%-20s %s %s#\n",DISK,PATH,$0 }' /etc/samba/smb.conf)"
bashio::log.blue "---------------------------------------------------"

View File

@@ -0,0 +1 @@
oneshot

View File

@@ -0,0 +1 @@
/etc/s6-overlay/s6-rc.d/init-samba/run

View File

@@ -0,0 +1,14 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Prepare the SMART config for disks
# ==============================================================================
if ! bashio::config.false "enable_smart"; then
smartctl --scan-open | while read -r -a device; do
bashio::log.info "Enabling S.M.A.R.T for ${device[0]}"
smartctl --smart=on --offlineauto=on --saveauto=on --quietmode=errorsonly "${device[0]}" || true
done
else
bashio::log.info "SMART support disabled in config"
fi

View File

@@ -0,0 +1 @@
oneshot

View File

@@ -0,0 +1 @@
/etc/s6-overlay/s6-rc.d/init-smartd/run

View File

@@ -0,0 +1,24 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Take down the S6 supervision tree based on service exit code
# ==============================================================================
declare topic
if bashio::config.false "mqtt_nexgen_entities"; then
if ! bashio::config.true "autodiscovery.disable_autoremove"; then
bashio::log.info "MQTT disk cleanup."
topic=$(bashio::config 'mqtt_topic')
if [ "$topic" = "null" ]; then topic="sambanas"; fi
mosquitto_sub -t "homeassistant/+/${topic}/+/config" --remove-retained -W 3 >/dev/null || true
mosquitto_sub -t "${topic}/state" --remove-retained -W 3 >/dev/null || true
bashio::log.info "MQTT disk cleanup Done."
fi
fi
if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then
bashio::log.warning "mqtt-handler crashed, halting add-on"
exec /run/s6/basedir/bin/halt
fi
bashio::log.info "mqtt-handler stopped"

View File

@@ -0,0 +1,171 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Start mqtt service for disk only
# ==============================================================================
readonly MAX_TIMEFRAME=60
readonly MIN_TIMEFRAME=10
readonly AVG_TIMEFRAME=$(((MAX_TIMEFRAME + MIN_TIMEFRAME) / 2))
if bashio::config.true "mqtt_nexgen_entities"; then
exec sleep infinity
fi
if [ -f /root/.config/mosquitto_pub ]; then
bashio::log.info "Starting the MQTT daemon for disks info..."
# Send autodiscovery entities
topic=$(bashio::config 'mqtt_topic')
if [ "$topic" = "null" ]; then topic="sambanas"; fi
# Send discovery messages.
if ! bashio::config.true "autodiscovery.disable_persistent"; then prs="-r"; fi
jdevice=$(jq -r -c -n --arg topic "$topic" --arg smbv "$(smbd -V | sed s/Version\ //)" --arg addon "$(bashio::addon.version)" '
{device:{
identifiers:[],
name: "SambaNas Physical Disk ",
hw_version: $addon,
sw_version: $smbv,
model: "SambaNas",
manufacturer: "@Dianlight",
via_device: $topic
}}')
device_scan=$(smartctl --scan-open)
if [ -z "$device_scan" ]; then
bashio::log.warning "No disk with S.M.A.R.T support found. Disable sensor report"
exec sleep infinity
fi
while read -r -a device; do
row=$(smartctl -A -l error -l selftest "${device[0]}" -j | jq '. * (.ata_smart_attributes.table // [] | INDEX(.name)) | del(.ata_smart_attributes.table)')
#bashio::log.info "2.2 ${row}"
for entity in device.name device.type device.protocol power_on_time.hours power_cycle_count temperature.current \
Raw_Read_Error_Rate.raw.value Reallocated_Sector_Ct.raw.value Wear_Leveling_Count.raw.value UDMA_CRC_Error_Count.raw.value \
ata_smart_error_log.summary.count ata_smart_self_test_log.standard.count; do
if [[ -z $(jq ".$entity // empty" <<<"$row") ]]; then
# bashio::log.info "2.2 Missing ${entity} in ${row}"
continue
fi
exmsg={}
etype=""
base=$(jq --arg topic "$topic" --arg entity "$entity" '
{
name:($topic+" "+$entity +" "+.device.info_name),
unique_id:((.device.name | explode | join("")) + "-" + ($entity|explode|join(""))),
value_template:("{{ value_json." +$entity+ "}}"),
state_topic:($topic + "/" + (.device.name | gsub("[^A-z]";"")) + "/state" ),
oth:{
uuid:.device.name | explode | join(""),
label:.device.name
}
}' <<<"$row")
case "$entity" in
device.name | device.type | device.protocol) #TEXT
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" '
{
mode: "text",
icon:"mdi:harddisk"
}' <<<"$row")
;;
power_on_time.hours) #Time
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" '
{
unit_of_measurement: "h",
device_class: "duration"
}' <<<"$row")
;;
power_cycle_count) #number
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" '
{
_unit_of_measurement: "",
icon:"mdi:power-cycle"
}' <<<"$row")
;;
Raw_Read_Error_Rate.raw.value | Reallocated_Sector_Ct.raw.value | Wear_Leveling_Count.raw.value | UDMA_CRC_Error_Count.raw.value | ata_smart_error_log.summary.count | ata_smart_self_test_log.standard.count) #number
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" '
{
_unit_of_measurement: "",
icon:"mdi:chart-box-outline"
}' <<<"$row")
;;
temperature.current) #temperature
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" '
{
unit_of_measurement: "°C",
device_class: "temperature",
_icon:"mdi:thermometer"
}' <<<"$row")
;;
*)
bashio::log.warning "Autodiscovery for $entity missing!"
;;
esac
#bashio::log.info "2.4 $base $exmsg"
msg=$(echo "$base" "$jdevice" "$exmsg" | jq -s 'add|.device.identifiers[.device.identifiers|length]=.oth.uuid|.device.name=(.device.name + .oth.label)|del(.oth)')
#bashio::log.debug "$msg"
mosquitto_pub "${prs}" -t "homeassistant/${etype}/${topic}/$(jq -r '.device.name | explode | join("")' <<<$row)-${entity//[\.\/]/-}/config" -m "$msg"
done
# bashio::log.info "2.3"
done <<<"${device_scan}"
while read -r -a device; do
mkfifo /tmp/mqtt-hanlder-${device[0]//\//}
# Send status message process
tail -F /tmp/mqtt-hanlder-${device[0]//\//} | mosquitto_pub -l -t "${topic}/${device[0]//\//}/state" &
done <<<"${device_scan}"
while read -r -a device; do
cdevice=${device[0]//\//}
shaOldMessage="-"
sleepTime=$AVG_TIMEFRAME
while true; do
#bashio::log.info "[$cdevice] ${shaOldMessage} $sleepTime"
status=$(smartctl -A -l error -l selftest "${device[0]}" -j | jq -c '. * (.ata_smart_attributes.table // [] | INDEX(.name)) | del(.ata_smart_attributes.table) | del(.local_time) | del(.smartctl) | del (.json_format_version)')
# Debug
shaMessage=$(sha1sum <<<"$status")
# bashio::log.green "[$cdevice] SleepTimes: $sleepTime $shaOldMessage] ${status}"
if [ "${shaOldMessage}" = "$shaMessage" ]; then
sleepTime=$((sleepTime * 2))
[ ${sleepTime} -gt $MAX_TIMEFRAME ] && sleepTime=$MAX_TIMEFRAME
else
# Send status message
if [ $sleepTime -gt $AVG_TIMEFRAME ]; then
sleepTime=$((sleepTime / 2))
else
sleepTime=$((sleepTime - MIN_TIMEFRAME))
fi
[ $sleepTime -le $MIN_TIMEFRAME ] && sleepTime=$MIN_TIMEFRAME
fi
jq -c --arg st "$sleepTime" --arg sh "$shaMessage" '. +
{
ref: {
mws: $st,
sha: $sh
}
}' <<<"${status}" >/tmp/mqtt-hanlder-$cdevice
shaOldMessage=$shaMessage
# Sleep
sleep ${sleepTime}
done &
sleep $((10 / $(wc -l <<<"$device_scan")))
done <<<"${device_scan}"
wait
else
exec sleep infinity
fi

View File

@@ -0,0 +1 @@
longrun

View File

@@ -0,0 +1,24 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Take down the S6 supervision tree based on service exit code
# ==============================================================================
declare topic
if bashio::config.false "mqtt_nexgen_entities"; then
if ! bashio::config.true "autodiscovery.disable_autoremove"; then
bashio::log.info "MQTT cleanup."
topic=$(bashio::config 'mqtt_topic')
if [ "$topic" = "null" ]; then topic="sambanas"; fi
mosquitto_sub -t "homeassistant/+/${topic}/+/config" --remove-retained -W 3 >/dev/null || true
mosquitto_sub -t "${topic}/state" --remove-retained -W 3 >/dev/null || true
bashio::log.info "MQTT cleanup Done."
fi
fi
if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then
bashio::log.warning "mqtt-handler crashed, halting add-on"
exec /run/s6/basedir/bin/halt
fi
bashio::log.info "mqtt-handler stopped"

View File

@@ -0,0 +1,177 @@
#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Start mqtt service
# ==============================================================================
readonly MAX_TIMEFRAME=60
readonly MIN_TIMEFRAME=5
readonly AVG_TIMEFRAME=$(((MAX_TIMEFRAME + MIN_TIMEFRAME) / 2))
if [ -f /root/.config/mosquitto_pub ]; then
bashio::log.info "Starting the MQTT daemon for partitions info..."
topic=$(bashio::config 'mqtt_topic' "sambanas")
# Send autodiscovery entities
if bashio::config.true "mqtt_nexgen_entities"; then
bashio::log.info "New MQTT integration"
host=$(bashio::config 'mqtt_host' "$(bashio::services 'mqtt' 'host')")
username=$(bashio::config 'mqtt_username' "$(bashio::services 'mqtt' 'username')")
password=$(bashio::config 'mqtt_password' "$(bashio::services 'mqtt' 'password')")
port=$(bashio::config 'mqtt_port' "$(bashio::services 'mqtt' 'port')")
log_level=$(bashio::string.lower "$(bashio::config log_level info)")
#bashio::log.info "New MQTT config ${host}:${port:-1883} ${username}:${password} ${topic}"
idleparam=""
if [ -p /tmp/hdidle.events ]; then
idleparam="-i /tmp/hdidle.events"
fi
exec /usr/bin/poetry -C /usr/local/bin/ run python /usr/local/bin/mqtt_daemon.py -b "${host}" -p "${port:-1883}" -u "${username}" -P "${password}" -t "${topic}" -v $(bashio::addon.version) ${idleparam} -l ${log_level^^}
else
bashio::log.info "MQTT integration"
# disks=$(awk 'BEGIN { ORS=""; print "["} /^ path = .*/g { printf "%s\"%s\"",separator,$3 ; separator="," } END { print "]" } ' /etc/samba/smb.conf)
disks=$(grep path /etc/samba/smb.conf | sed 's/.*path\ =\ //' | jq --raw-input --slurp 'split("\n") | map(select(. != ""))')
blk=$(lsblk -b -no PARTUUID,NAME,LABEL,FSTYPE,MOUNTPOINTS -J -y)
jdisks=$(jq --argjson disks "$disks" 'reduce (.blockdevices[].children[]? |select(.mountpoints? - $disks != .mountpoints) ) as $i ({};.[$i.name] = $i)' <<<${blk})
# Send discovery messages.
if ! bashio::config.true "autodiscovery.disable_persistent"; then prs="-r"; fi
#bashio::log.info $device
device=$(jq -r -c -n --arg topic "$topic" --arg smbv "$(smbd -V | sed s/Version\ //)" --arg addon "$(bashio::addon.version)" '
{device:{
identifiers:[],
name: "SambaNas Disk ",
hw_version: $addon,
sw_version: $smbv,
model: "SambaNas",
manufacturer: "@Dianlight",
via_device: $topic
}}')
for row in $(jq -r '.|map(.|@base64)|.[]' <<<"$jdisks"); do
for entity in name label mountpoints fssize fsused fsuse_pct fsavail fstype iostat.tps iostat.kB_read/s iostat.kB_wrtn/s iostat.kB_dscd/s iostat.kB_read iostat.kB_wrtn iostat.kB_dscd; do
exmsg={}
etype=""
base=$(jq --arg topic "$topic" --arg entity "$entity" -R '@base64d|fromjson|
{
name:($topic+" "+$entity +" "+ .label),
unique_id:(.partuuid +"-"+ ($entity|explode|join(""))),
value_template:("{{ value_json." + .name + "." +$entity+ "}}"),
state_topic:($topic + "/state"),
oth:{
partuuid:.partuuid,
name:.name,
label:.label,
root:("/dev/" + .name[:-1])
}
}' <<<"$row")
case "$entity" in
name | label | fstype | mountpoints) #TEXT
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" -R '@base64d|fromjson|
{
mode: "text",
icon:"mdi:harddisk"
}' <<<"$row")
;;
fssize | fsused | fsavail) #DATA_SIZE (Byte)
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" -R '@base64d|fromjson|
{
unit_of_measurement: "B",
device_class: "data_size",
}' <<<"$row")
;;
iostat.kB_read | iostat.kB_wrtn | iostat.kB_dscd) #DATA_SIZE (KB)
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" -R '@base64d|fromjson|
{
unit_of_measurement: "kB",
device_class: "data_size",
}' <<<"$row")
;;
iostat.kB_read/s | iostat.kB_wrtn/s | iostat.kB_dscd/s) #data_rate
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entityb "${entity%.*}" --arg entityd "${entity##*.}" -R '@base64d|fromjson|
{
unit_of_measurement: "kB/s",
device_class: "data_rate",
value_template:("{{ value_json." + .name + "." +$entityb+ "['"'"'" + $entityd + "'"'"']}}"),
icon:"mdi:database-refresh"
}' <<<"$row")
;;
iostat.tps) #TPS
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" -R '@base64d|fromjson|
{
unit_of_measurement: "tps",
icon:"mdi:database-search"
}' <<<"$row")
;;
fsuse_pct) # PERCENT
etype="sensor"
exmsg=$(jq --arg topic "$topic" --arg entity "$entity" -R '@base64d|fromjson|
{
unit_of_measurement: "%",
icon:"mdi:database-eye"
}' <<<"$row")
;;
*)
bashio::log.warning "Autodiscovery for $entity missing!"
;;
esac
msg=$(echo "$base" "$device" "$exmsg" | jq -s 'add|.device.identifiers[.device.identifiers|length]=.oth.partuuid|.device.name=(.device.name + .oth.label)|.device.via_device=(.oth.root | explode | join(""))|del(.oth)')
#bashio::log.debug "$msg"
mosquitto_pub "${prs}" -t "homeassistant/${etype}/${topic}/$(jq -R -r '@base64d|fromjson|.partuuid' <<<"$row")-${entity//[\.\/]/-}/config" -m "$msg"
done
done
mkfifo /tmp/mqtt-hanlder
# Send status message process
tail -F /tmp/mqtt-hanlder | mosquitto_pub -l -t "${topic}/state" &
sleepTime=$AVG_TIMEFRAME
shaOldMessage="-"
while true; do
blk=$(lsblk -b -no NAME,LABEL,FSSIZE,FSUSED,FSUSE%,FSAVAIL,FSTYPE,MOUNTPOINTS -J -y | jq 'walk(if type == "object" and .fsuse_pct != null then .fsuse_pct|=(rtrimstr("%")|tonumber) else . end)')
liostat=$(/usr/bin/iostat "$(jq -r '.|map(.name)|.[]' <<<"""$jdisks""")" -k -d -p -o JSON)
status=$(jq -c --argjson disks "$disks" --argjson iostat "$liostat" 'reduce (.blockdevices[].children[]? |select(.mountpoints? - $disks != .mountpoints) ) as $i ({};.[$i.name] = $i+{iostat:($iostat.sysstat.hosts[0].statistics[0].disk[] | select(.disk_device==$i.name))})' <<<"${blk}")
# Send status message
shaMessage=$(sha1sum <<<"$status")
if [ "$shaOldMessage" = "$shaMessage" ]; then
sleepTime=$((sleepTime * 2))
[ $sleepTime -gt $MAX_TIMEFRAME ] && sleepTime=$MAX_TIMEFRAME
else
# Send status message
if [ $sleepTime -gt $AVG_TIMEFRAME ]; then
sleepTime=$((sleepTime / 2))
else
sleepTime=$((sleepTime - MIN_TIMEFRAME))
fi
[ $sleepTime -le $MIN_TIMEFRAME ] && sleepTime=$MIN_TIMEFRAME
fi
jq -c --arg st "$sleepTime" --arg sh "$shaMessage" '. +
{
ref: {
mws: $st,
sha: $sh
}
}' <<<"${status}" >/tmp/mqtt-hanlder
shaOldMessage=$shaMessage
# Sleep
sleep $sleepTime
done
fi
else
exec sleep infinity
fi

View File

@@ -0,0 +1 @@
longrun

View File

@@ -0,0 +1,10 @@
#!/usr/bin/with-contenv bashio
# ==============================================================================
# Take down the S6 supervision tree based on service exit code
# ==============================================================================
if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then
bashio::log.warning "nmbd crashed, halting add-on"
exec /run/s6/basedir/bin/halt
fi
bashio::log.info "nmbd stopped"

View File

@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# ==============================================================================
# Start nmbd service
# ==============================================================================
exec nmbd \
--foreground \
--debug-stdout \
--no-process-group

View File

@@ -0,0 +1 @@
longrun

View File

@@ -0,0 +1,12 @@
#!/usr/bin/with-contenv bashio
# ==============================================================================
# Take down the S6 supervision tree based on service exit code
# ==============================================================================
if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then
bashio::log.warning "smbd crashed, halting add-on"
bashio::log.info "Dump SMB configuration:"
cat /etc/samba/smb.conf >&2
exec /run/s6/basedir/bin/halt
fi
bashio::log.info "smbd stopped"

View File

@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# ==============================================================================
# Start smbd service
# ==============================================================================
exec smbd \
--foreground \
--debug-stdout \
--no-process-group

View File

@@ -0,0 +1 @@
longrun

View File

@@ -0,0 +1,10 @@
#!/usr/bin/with-contenv bashio
# ==============================================================================
# Take down the S6 supervision tree based on service exit code
# ==============================================================================
if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then
bashio::log.warning "wsdd crashed, halting add-on"
exec /run/s6/basedir/bin/halt
fi
bashio::log.info "wsdd stopped"

View File

@@ -0,0 +1,46 @@
#!/usr/bin/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Start wsdd service
# ==============================================================================
declare SMB_GROUP
declare SMB_HOST
SMB_GROUP=$(grep -i '^\s*workgroup\s*=' /etc/samba/smb.conf | cut -f2 -d= | tr -d '[:blank:]')
SMB_HOST=$(grep -i '^\s*netbios name\s*=' /etc/samba/smb.conf | cut -f2 -d= | tr -d '[:blank:]')
if bashio::config.true 'bind_all_interfaces'; then
interfaces+=" "
elif bashio::config.has_value 'interfaces'; then
bashio::log.info "Interfaces from config: $(bashio::config 'interfaces')"
for interface in $(bashio::config 'interfaces'); do
if [ -d "/sys/class/net/${interface}" ]; then
interfaces+=("-i ${interface}")
else
bashio::log.warning "Interface ${interface} not found, skipping."
fi
done
else
# Get supported interfaces
for interface in $(bashio::network.interfaces); do
interfaces+=("-i ${interface}")
done
fi
#if [ ${#interfaces[@]} -eq 0 ]; then
# bashio::exit.nok 'No supported interfaces found to bind on.'
#fi
#bashio::log.info "Interfaces: $(printf '%s ' "${interfaces[@]}")"
if bashio::config.true 'wsdd2'; then
bashio::log.info "Starting the WSDD2 daemon $(printf '%s ' "${interfaces[@]}") for ${SMB_GROUP}/${SMB_HOST}..."
setcap CAP_NET_RAW+ep /usr/sbin/wsdd2
# shellcheck disable=SC2046
exec /usr/sbin/wsdd2 -t -u -w $(printf '%s ' "${interfaces[@]}") -H "${SMB_HOST}" -b vendor:homeassistant,model:sambanas
elif bashio::config.true 'wsdd'; then
bashio::log.info "Starting the WSDD daemon $(printf '%s ' "${interfaces[@]}") for ${SMB_GROUP}/${SMB_HOST}..."
# shellcheck disable=SC2046
exec wsdd -v $(printf '%s ' "${interfaces[@]}") -n "${SMB_HOST}" -w "${SMB_GROUP}"
else
exec sleep infinity
fi

View File

@@ -0,0 +1 @@
longrun