Created
July 29, 2021 17:23
-
-
Save noodny/65f116b3a9da9ce1b784e355b4c52186 to your computer and use it in GitHub Desktop.
Update samba shares as drives are mounted / unmounted on an RPi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { readdirSync, watch, readFileSync, writeFileSync } from 'fs'; | |
import { exec } from 'child_process'; | |
const PATHNAME = '/media/pi'; | |
const SMB_CONF = '/etc/samba/smb.conf'; | |
let currentMedia = []; | |
function getMedia() { | |
return readdirSync(PATHNAME); | |
} | |
function readSmbConf() { | |
return readFileSync(SMB_CONF).toString(); | |
} | |
function updateSmbConf(shares) { | |
const conf = readSmbConf(); | |
const entryString = '###### auto shares setup'; | |
const regexp = new RegExp(`${entryString}.*`, 's'); | |
const updated = conf.replace(regexp, `${entryString}\n${shares.map(share => buildShare(share)).join('\n')}`) | |
writeFileSync(SMB_CONF, updated); | |
restartSmb() | |
} | |
function restartSmb() { | |
exec('sudo systemctl restart smbd'); | |
} | |
function buildShare(share) { | |
return ` | |
[${share}] | |
comment = ${share} Mounted Media | |
path = ${PATHNAME}/${share} | |
browseable = yes | |
read only = yes | |
guest ok = no | |
force user = pi | |
` | |
} | |
watch(PATHNAME, (eventType, filename) => { | |
const updated = getMedia() | |
if(updated.length !== currentMedia.length) { | |
updateSmbConf(updated) | |
console.log('Updating shares') | |
} else { | |
console.log('Skipping shares update') | |
} | |
currentMedia = updated; | |
}); | |
currentMedia = getMedia() | |
updateSmbConf(currentMedia); | |
console.log('Shares initialized') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment