Skip to content

Instantly share code, notes, and snippets.

@noodny
Created July 29, 2021 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noodny/65f116b3a9da9ce1b784e355b4c52186 to your computer and use it in GitHub Desktop.
Save noodny/65f116b3a9da9ce1b784e355b4c52186 to your computer and use it in GitHub Desktop.
Update samba shares as drives are mounted / unmounted on an RPi
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