#!/bin/sh
set -eu
P=/var/packages/SynoClone/target
V=/var/packages/SynoClone/var
mkdir -p "$V"
chmod 755 "$V"
stop_one() { f="$V/$1.pid"; if [ -f "$f" ]; then p=$(cat "$f"); case "$p" in ''|*[!0-9]*) return 1;; esac; if [ -r "/proc/$p/cmdline" ] && tr '\000' ' ' < "/proc/$p/cmdline" | grep -Fq "$2"; then kill "$p"; fi; rm -f "$f"; fi; }
case "$1" in
start)
[ -f "$V/enable-pxe" ] || exit 0
ip -4 addr show dev ovs_bond0 | grep -q '192.168.0.100/24' || exit 1
[ -d /volume1/nclone ] || { echo 'Creer le partage nclone dans DSM' >&2; exit 1; }
mkdir -p "$V/tftp/pxelinux.cfg"
chmod 755 "$V/tftp" "$V/tftp/pxelinux.cfg"
cp "$P/tftpboot/"pxelinux.0 "$P/tftpboot/"vmlinuz "$P/tftpboot/"initrd.img "$V/tftp/"
cat > "$V/tftp/pxelinux.cfg/default" <<'CFG'
DEFAULT cz
LABEL cz
KERNEL vmlinuz
APPEND initrd=initrd.img boot=live hostname=nclone config union=overlayfs noswap nolocales edd=on nomodeset fetch=http://192.168.0.100:8089/filesystem.squashfs ocs_live_batch=no ocs_prerun="wget -O /tmp/autorun http://192.168.0.100:8089/autorun" ocs_live_run="sh /tmp/autorun" ocs_lang=en_US.UTF-8
IPAPPEND 3
CFG
cat > "$V/dnsmasq.conf" <<CFG
port=0
interface=ovs_bond0
bind-interfaces
log-dhcp
enable-tftp
tftp-root=$V/tftp
dhcp-range=192.168.0.0,proxy,255.255.255.0
pxe-prompt="Press F8 for SynoClone",10
pxe-service=x86PC,"Boot from local disk"
pxe-service=x86PC,"Start SynoClone",pxelinux
pid-file=$V/dnsmasq.pid
log-facility=$V/dnsmasq.log
CFG
if [ -f "$V/http.pid" ] || [ -f "$V/dnsmasq.pid" ]; then echo "Stopper le service avant de le relancer" >&2; exit 1; fi
"$P/bin/dnsmasq" --test -C "$V/dnsmasq.conf"
/usr/bin/python3 "$P/http.py" > "$V/http.log" 2>&1 & echo $! > "$V/http.pid"
sleep 1
kill -0 "$(cat "$V/http.pid")" || exit 1
"$P/bin/dnsmasq" -C "$V/dnsmasq.conf" || { stop_one http "$P/http.py"; exit 1; }
;;
stop) stop_one dnsmasq "$P/bin/dnsmasq"; stop_one http "$P/http.py";;
status) [ -f "$V/enable-pxe" ] || exit 0; for s in dnsmasq http; do [ -f "$V/$s.pid" ] && kill -0 "$(cat "$V/$s.pid")" 2>/dev/null || exit 3; done;;
log) echo "$V/dnsmasq.log";;
*) exit 1;; esac
