1
0

install-complete.sh 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831
  1. #!/bin/bash
  2. set -eo pipefail
  3. # WaouW v2.0 COMPLETE - Installation Script
  4. # Compatible: Raspberry Pi OS, Ubuntu ARM64
  5. # Requirements: Docker, Docker Compose
  6. # Features: Email, Cloud, VPN, Security, Monitoring
  7. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  8. PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
  9. WAOUW_USER="waouw"
  10. WAOUW_HOME="/opt/waouw"
  11. # Garantir que $WAOUW_HOME/DEPLOY et les autres sous-dossiers sont accessibles
  12. if [ "$SCRIPT_DIR" != "$WAOUW_HOME/DEPLOY" ] && [ ! -e "$WAOUW_HOME/DEPLOY" ]; then
  13. ln -sfn "$SCRIPT_DIR" "$WAOUW_HOME/DEPLOY"
  14. fi
  15. for subdir in BACKEND UI DEVICE_AGENT SYNC_MANAGER BACKUP_MANAGER; do
  16. if [ -d "$SCRIPT_DIR/../$subdir" ] && [ ! -e "$WAOUW_HOME/$subdir" ]; then
  17. ln -sfn "$SCRIPT_DIR/../$subdir" "$WAOUW_HOME/$subdir"
  18. fi
  19. done
  20. # Désactiver IPv6 complètement (évite les DNS IPv6 link-local qui cassent les pulls Docker)
  21. sysctl -w net.ipv6.conf.all.disable_ipv6=1 2>/dev/null || true
  22. sysctl -w net.ipv6.conf.default.disable_ipv6=1 2>/dev/null || true
  23. sysctl -w net.ipv6.conf.eth0.disable_ipv6=1 2>/dev/null || true
  24. sysctl -w net.ipv6.conf.lo.disable_ipv6=1 2>/dev/null || true
  25. echo "net.ipv6.conf.all.disable_ipv6=1" >> /etc/sysctl.conf 2>/dev/null || true
  26. echo "net.ipv6.conf.default.disable_ipv6=1" >> /etc/sysctl.conf 2>/dev/null || true
  27. # DNS fiable: forcer systemd-resolved en IPv4 uniquement
  28. mkdir -p /etc/systemd/resolved.conf.d
  29. echo -e "[Resolve]\nDNS=8.8.8.8 8.8.4.4\nFallbackDNS=1.1.1.1" > /etc/systemd/resolved.conf.d/waouw-dns.conf
  30. systemctl restart systemd-resolved 2>/dev/null || true
  31. # CRITIQUE — override du watchdog systemd Raspberry Pi OS
  32. # Le drop-in /usr/lib/systemd/system.conf.d/40-rpi-enable-watchdog.conf force
  33. # RuntimeWatchdogSec=1m, ce qui est trop court pour un Pi 4 qui doit booter
  34. # 24 containers Docker en parallele (load avg > 7 au boot). Sans override,
  35. # le watchdog hardware reset le SoC pendant le boot -> dirty filesystem ext4
  36. # -> reboot loop. Cause documentee dans memory + DEPLOY/systemd/.
  37. # Voir aussi : DEPLOY/systemd/99-waouw-watchdog.conf (template authoritative)
  38. mkdir -p /etc/systemd/system.conf.d
  39. if [ -f "$SCRIPT_DIR/systemd/99-waouw-watchdog.conf" ]; then
  40. cp "$SCRIPT_DIR/systemd/99-waouw-watchdog.conf" /etc/systemd/system.conf.d/99-waouw-watchdog.conf
  41. else
  42. # Fallback inline si le template n'a pas ete copie
  43. cat > /etc/systemd/system.conf.d/99-waouw-watchdog.conf << 'WDOG_EOF'
  44. [Manager]
  45. RuntimeWatchdogSec=10min
  46. RebootWatchdogSec=5min
  47. WDOG_EOF
  48. fi
  49. systemctl daemon-reexec 2>/dev/null || true
  50. # Forcer Docker à utiliser le DNS IPv4 (indépendant du système)
  51. mkdir -p /etc/docker
  52. echo '{"dns": ["8.8.8.8", "8.8.4.4"]}' > /etc/docker/daemon.json
  53. mkdir -p /var/log/waouw-deploy
  54. [ -f "$SCRIPT_DIR/waouw-deploy-log.sh" ] && _WAOUW_SCRIPT="install-complete" . "$SCRIPT_DIR/waouw-deploy-log.sh"
  55. _deploy_log() { waouw_deploy_log "INFO" "$@" 2>/dev/null || log "$@"; }
  56. _deploy_step() { waouw_deploy_step "$@" 2>/dev/null || true; }
  57. _deploy_err() { waouw_deploy_error "$@" 2>/dev/null || error "$@"; }
  58. # Colors for output
  59. RED='\033[0;31m'
  60. GREEN='\033[0;32m'
  61. YELLOW='\033[1;33m'
  62. BLUE='\033[0;34m'
  63. NC='\033[0m' # No Color
  64. log() {
  65. echo -e "${GREEN}[INFO]${NC} $1"
  66. }
  67. warn() {
  68. echo -e "${YELLOW}[WARN]${NC} $1"
  69. }
  70. error() {
  71. echo -e "${RED}[ERROR]${NC} $1"
  72. }
  73. success() {
  74. echo -e "${BLUE}[SUCCESS]${NC} $1"
  75. }
  76. fix_clock() {
  77. timedatectl set-ntp true 2>/dev/null || true
  78. systemctl restart systemd-timesyncd 2>/dev/null || true
  79. local http_date=""
  80. if command -v python3 >/dev/null 2>&1; then
  81. http_date="$(python3 - <<'PY'
  82. import urllib.request
  83. for url in ("http://admin.waouw.eu", "http://deb.debian.org"):
  84. try:
  85. with urllib.request.urlopen(url, timeout=10) as response:
  86. print(response.headers.get("Date", ""))
  87. break
  88. except Exception:
  89. pass
  90. PY
  91. )"
  92. fi
  93. http_date="$(printf '%s\n' "$http_date" | sed '/^$/d' | head -n1)"
  94. if [[ -n "$http_date" ]]; then
  95. local remote_ts=""
  96. local now_ts=""
  97. remote_ts="$(date -u -d "$http_date" '+%s' 2>/dev/null || true)"
  98. now_ts="$(date -u '+%s' 2>/dev/null || echo 0)"
  99. if [[ -n "$remote_ts" && "$remote_ts" -gt 1700000000 ]] && { [[ "$now_ts" -lt $((remote_ts - 300)) ]] || [[ "$now_ts" -gt $((remote_ts + 86400)) ]]; }; then
  100. date -u -s "@$remote_ts" >/dev/null 2>&1 || true
  101. hwclock --systohc >/dev/null 2>&1 || true
  102. _deploy_log "Horloge système recalée depuis la date HTTP: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
  103. fi
  104. fi
  105. }
  106. check_requirements() {
  107. log "Vérification des prérequis..."
  108. # Check OS (non-interactif: on continue avec avertissement)
  109. if ! grep -Eq "Raspberry Pi OS|Raspbian|Debian|Ubuntu" /etc/os-release 2>/dev/null; then
  110. warn "OS non officiellement supporté détecté; poursuite automatique (mode non-interactif)."
  111. fi
  112. # Check architecture
  113. ARCH=$(uname -m)
  114. if [[ "$ARCH" != "aarch64" && "$ARCH" != "armv7l" && "$ARCH" != "x86_64" ]]; then
  115. error "Architecture non supportée: $ARCH"
  116. exit 1
  117. fi
  118. # Privileges: allow root to keep flow non-interactive
  119. if [[ $EUID -ne 0 ]]; then
  120. warn "Execution non-root detectee, sudo sera requis pour certaines etapes."
  121. fi
  122. # Check available memory (minimum 2GB recommended)
  123. MEMORY_GB=$(free -g | awk '/^Mem:/ {print $2}')
  124. if [[ $MEMORY_GB -lt 2 ]]; then
  125. warn "Mémoire faible détectée (${MEMORY_GB}GB). 2GB+ recommandés pour tous les services."
  126. fi
  127. # Check disk space (minimum 8GB free)
  128. DISK_FREE_GB=$(df / | awk 'NR==2 {print int($4/1024/1024)}')
  129. if [[ $DISK_FREE_GB -lt 8 ]]; then
  130. error "Espace disque insuffisant. 8GB+ requis, ${DISK_FREE_GB}GB disponible."
  131. exit 1
  132. fi
  133. success "Prérequis validés"
  134. }
  135. install_docker() {
  136. if command -v docker &> /dev/null && docker compose version &> /dev/null; then
  137. log "Docker déjà installé"
  138. return
  139. fi
  140. log "Installation de Docker..."
  141. curl -fsSL https://get.docker.com | sh
  142. sudo usermod -aG docker $USER
  143. sudo systemctl enable docker
  144. sudo systemctl start docker
  145. success "Docker installé"
  146. }
  147. # Install additional system dependencies
  148. install_system_dependencies() {
  149. log "Installation des dépendances système..."
  150. fix_clock
  151. # Update package lists
  152. sudo apt-get update
  153. # Préconfigurer Postfix pour éviter tout dialogue interactif
  154. sudo debconf-set-selections <<< "postfix postfix/mailname string $(hostname -f)"
  155. sudo debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
  156. export DEBIAN_FRONTEND=noninteractive
  157. # Install additional packages for email, VPN, security
  158. sudo DEBIAN_FRONTEND=noninteractive apt-get install -y \
  159. ufw \
  160. fail2ban \
  161. postfix \
  162. dovecot-core \
  163. avahi-daemon \
  164. avahi-utils \
  165. libnss-mdns \
  166. openvpn \
  167. easy-rsa \
  168. certbot \
  169. apache2-utils \
  170. jq \
  171. curl \
  172. wget \
  173. rsync \
  174. lsyncd \
  175. rclone \
  176. tree \
  177. htop \
  178. iotop \
  179. net-tools \
  180. dnsutils \
  181. openssl \
  182. wireguard-tools \
  183. mailutils
  184. # Enable mDNS so the box is reachable via waouw.local
  185. # Restrict Avahi to eth0/wlan0 only - Docker veth interfaces would break mDNS when containers restart
  186. if ! grep -q '^allow-interfaces=' /etc/avahi/avahi-daemon.conf 2>/dev/null; then
  187. sudo sed -i '/^\[server\]/a allow-interfaces=eth0,wlan0' /etc/avahi/avahi-daemon.conf
  188. fi
  189. sudo systemctl enable avahi-daemon
  190. sudo systemctl restart avahi-daemon || sudo systemctl start avahi-daemon
  191. # Fix WiFi Raspberry Pi OS Bookworm : brcmfmac-wcc doit être chargé AVANT brcmfmac
  192. # sinon le module principal échoue à binder et le WiFi n'est pas détecté.
  193. sudo tee /etc/modprobe.d/wifi-wcc.conf > /dev/null <<'WIFI_EOF'
  194. # WaouW : fix WiFi Bookworm — softdep force l'ordre de chargement
  195. softdep brcmfmac pre: brcmfmac-wcc
  196. WIFI_EOF
  197. sudo update-initramfs -u 2>/dev/null || true
  198. success "Dépendances système installées"
  199. }
  200. create_waouw_user() {
  201. if id "$WAOUW_USER" &>/dev/null; then
  202. log "Utilisateur $WAOUW_USER existe déjà"
  203. else
  204. log "Création de l'utilisateur $WAOUW_USER..."
  205. sudo useradd -r -s /bin/bash -d "$WAOUW_HOME" -m "$WAOUW_USER"
  206. fi
  207. # Important: au premier boot, le groupe docker n'existe pas encore.
  208. # Si l'utilisateur a été créé avant l'installation de Docker, il faut
  209. # rejouer explicitement ces rattachements.
  210. sudo usermod -aG docker "$WAOUW_USER" 2>/dev/null || true
  211. sudo usermod -aG mail "$WAOUW_USER" 2>/dev/null || true
  212. sudo usermod -aG ssl-cert "$WAOUW_USER" 2>/dev/null || true
  213. success "Utilisateur $WAOUW_USER prêt"
  214. }
  215. create_directories() {
  216. log "Création des répertoires..."
  217. # Main directories
  218. sudo mkdir -p "$WAOUW_HOME"/{config,data,logs,backups,scripts,certs}
  219. # Service-specific directories
  220. sudo mkdir -p "$WAOUW_HOME"/data/{postgres,redis,traefik}
  221. sudo mkdir -p "$WAOUW_HOME"/data/{nextcloud,roundcube,postfix,dovecot}
  222. sudo mkdir -p "$WAOUW_HOME"/data/{grafana,prometheus,graylog,elasticsearch}
  223. sudo mkdir -p "$WAOUW_HOME"/data/{fail2ban,openvpn}
  224. # Log directories
  225. sudo mkdir -p /var/log/waouw
  226. # Mail directories
  227. sudo mkdir -p /var/mail/vhosts
  228. sudo mkdir -p /etc/postfix/sql
  229. sudo mkdir -p /etc/dovecot/sql
  230. # Certificates directory
  231. sudo mkdir -p /etc/waouw/certs
  232. # Set ownership
  233. sudo chown -R "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME"
  234. sudo chown -R "$WAOUW_USER:$WAOUW_USER" /var/log/waouw
  235. sudo chown -R mail:mail /var/mail/vhosts
  236. sudo chown -R 999:999 /etc/waouw
  237. # Set permissions
  238. sudo chmod -R 755 "$WAOUW_HOME"
  239. sudo chmod 755 /etc/waouw
  240. sudo mkdir -p /etc/waouw/keys /etc/waouw/certs
  241. sudo chmod 755 /etc/waouw/keys
  242. sudo chmod -R 770 /var/mail/vhosts
  243. sudo chmod -R 750 /etc/waouw/certs
  244. # Pre-create avahi files so the backend container (user waouw) can write to them
  245. sudo touch /etc/waouw/avahi-site-hosts /etc/waouw/avahi-reload-signal
  246. sudo chown "$WAOUW_USER:$WAOUW_USER" /etc/waouw/avahi-site-hosts /etc/waouw/avahi-reload-signal
  247. # Backend container runs as uid 999, host user is typically uid 1000.
  248. # Keep these files world-writable to avoid mDNS registration failures.
  249. sudo chmod 666 /etc/waouw/avahi-site-hosts /etc/waouw/avahi-reload-signal
  250. # Sites data directory for FTP access (bind-mounted in CMS containers)
  251. sudo mkdir -p /opt/waouw/sites-data
  252. sudo chmod 777 /opt/waouw/sites-data
  253. # FTP pending directory (backend writes requests, host script processes)
  254. sudo mkdir -p /etc/waouw/ftp-pending
  255. sudo chmod 777 /etc/waouw/ftp-pending
  256. success "Répertoires créés"
  257. }
  258. ensure_device_runtime_files() {
  259. log "Préparation des fichiers runtime /etc/waouw..."
  260. local device_id=""
  261. if sudo test -s /etc/waouw/device_id; then
  262. device_id=$(sudo tr -d '\r\n' < /etc/waouw/device_id || true)
  263. fi
  264. if [[ -z "$device_id" ]] && [[ -r /proc/cpuinfo ]]; then
  265. device_id=$(awk '/^Serial/ {print $3}' /proc/cpuinfo | tail -1)
  266. fi
  267. if [[ -z "$device_id" ]] && [[ -r /etc/machine-id ]]; then
  268. device_id=$(tr -d '\r\n' < /etc/machine-id | cut -c1-16)
  269. fi
  270. if [[ -n "$device_id" ]]; then
  271. echo -n "$device_id" | sudo tee /etc/waouw/device_id >/dev/null
  272. sudo chmod 644 /etc/waouw/device_id
  273. sudo chown 999:999 /etc/waouw/device_id
  274. fi
  275. sudo touch /etc/waouw/claim_code /etc/waouw/desired_hostname /etc/waouw/onboarding-state.json
  276. sudo chown 999:999 /etc/waouw/claim_code /etc/waouw/desired_hostname /etc/waouw/onboarding-state.json
  277. sudo chmod 644 /etc/waouw/claim_code /etc/waouw/desired_hostname /etc/waouw/onboarding-state.json
  278. sudo mkdir -p /etc/waouw/keys
  279. sudo chown 999:999 /etc/waouw/keys
  280. sudo chmod 755 /etc/waouw/keys
  281. sudo sh -c 'for f in /etc/waouw/keys/*; do [ -f "$f" ] && chown 999:999 "$f" && chmod 644 "$f"; done' || true
  282. success "Fichiers runtime /etc/waouw prêts"
  283. }
  284. install_activation_bootstrap() {
  285. log "Configuration activation (bootstrap)..."
  286. # Copier le token bootstrap depuis /boot vers /etc/waouw
  287. local BOOT_TOKEN=""
  288. if [[ -f "/boot/waouw-bootstrap-token.txt" ]]; then
  289. BOOT_TOKEN=$(tr -d '\r\n' < "/boot/waouw-bootstrap-token.txt" || true)
  290. elif [[ -f "/boot/firmware/waouw-bootstrap-token.txt" ]]; then
  291. BOOT_TOKEN=$(tr -d '\r\n' < "/boot/firmware/waouw-bootstrap-token.txt" || true)
  292. fi
  293. if [[ -n "$BOOT_TOKEN" ]]; then
  294. sudo mkdir -p /etc/waouw/keys
  295. echo -n "$BOOT_TOKEN" | sudo tee /etc/waouw/bootstrap_token >/dev/null
  296. # 644: lisible par le container backend (UID 999) et l'hôte (UID 1000)
  297. # Le token bootstrap n'est pas un secret à long terme (usage unique par device)
  298. sudo chmod 644 /etc/waouw/bootstrap_token
  299. sudo chown "$WAOUW_USER:$WAOUW_USER" /etc/waouw/bootstrap_token
  300. success "Token bootstrap installé (/etc/waouw/bootstrap_token)"
  301. else
  302. warn "Token bootstrap absent sur /boot. L'activation online ne fonctionnera pas."
  303. fi
  304. # Lire l'URL du waouw-admin online. Par défaut, on pointe sur la prod.
  305. local ADMIN_URL="https://admin.waouw.eu"
  306. if [[ -f "/boot/waouw-admin-url.txt" ]]; then
  307. ADMIN_URL=$(tr -d '\r\n' < "/boot/waouw-admin-url.txt" || true)
  308. elif [[ -f "/boot/firmware/waouw-admin-url.txt" ]]; then
  309. ADMIN_URL=$(tr -d '\r\n' < "/boot/firmware/waouw-admin-url.txt" || true)
  310. fi
  311. if [[ -n "$ADMIN_URL" ]]; then
  312. export WAOUW_ADMIN_URL="$ADMIN_URL"
  313. success "WAOUW_ADMIN_URL détectée: $WAOUW_ADMIN_URL"
  314. fi
  315. }
  316. copy_waouw_files() {
  317. log "Vérification des fichiers WaouW..."
  318. # Files are already in place from the archive extraction
  319. # Just ensure correct ownership
  320. sudo chown -R "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME"
  321. success "Fichiers vérifiés"
  322. }
  323. install_update_cli() {
  324. log "Installation de l'outil de mise à jour..."
  325. sudo mkdir -p /usr/local/bin
  326. sudo mkdir -p /var/log/waouw/updates
  327. # Copy hardened update scripts from repo
  328. sudo cp -f "$WAOUW_HOME/DEPLOY/scripts/waouw-update" /usr/local/bin/waouw-update
  329. sudo cp -f "$WAOUW_HOME/DEPLOY/scripts/waouw-auto-update.sh" /usr/local/bin/waouw-auto-update.sh
  330. sudo chmod +x /usr/local/bin/waouw-update /usr/local/bin/waouw-auto-update.sh
  331. # Systemd path unit: watches for pending-update.json trigger file
  332. sudo tee /etc/systemd/system/waouw-update.path > /dev/null <<'EOF'
  333. [Unit]
  334. Description=Watch for WaouW update trigger
  335. [Path]
  336. PathChanged=/var/lib/docker/volumes/waouw_backup_data/_data/updates/pending-update.json
  337. PathModified=/var/lib/docker/volumes/waouw_backup_data/_data/updates/pending-update.json
  338. [Install]
  339. WantedBy=multi-user.target
  340. EOF
  341. sudo tee /etc/systemd/system/waouw-update.service > /dev/null <<'EOF'
  342. [Unit]
  343. Description=Apply WaouW update
  344. [Service]
  345. Type=oneshot
  346. ExecStart=/usr/local/bin/waouw-auto-update.sh
  347. TimeoutStartSec=1200
  348. EOF
  349. sudo systemctl daemon-reload
  350. sudo systemctl enable waouw-update.path
  351. sudo systemctl start waouw-update.path
  352. success "Outil de mise à jour installé (scripts + systemd trigger)"
  353. }
  354. generate_config() {
  355. log "Génération de la configuration..."
  356. # Reprise d'installation: si un .env existe déjà, on réutilise ses secrets
  357. # pour éviter de désynchroniser Postgres et les autres services stateful.
  358. if [[ -f "$WAOUW_HOME/.env" ]]; then
  359. set -a
  360. # shellcheck disable=SC1090
  361. . "$WAOUW_HOME/.env" || true
  362. set +a
  363. log "Réutilisation des secrets existants depuis $WAOUW_HOME/.env"
  364. fi
  365. # Generate random passwords (openssl rand, pas de dépendance à pwgen)
  366. _rndpw() { openssl rand -base64 $(( $1 * 2 )) 2>/dev/null | tr -d '/+=\n' | head -c "$1"; }
  367. DB_PASSWORD=${POSTGRES_PASSWORD:-$(_rndpw 32)}
  368. JWT_SECRET=${JWT_SECRET_KEY:-$(openssl rand -hex 32)}
  369. DEVICE_SECRET=${DEVICE_HMAC_SECRET:-$(openssl rand -hex 32)}
  370. MAIL_DB_PASSWORD=${MAIL_MYSQL_PASSWORD:-$(_rndpw 32)}
  371. NEXTCLOUD_ADMIN_PASSWORD=${NEXTCLOUD_ADMIN_PASSWORD:-$(_rndpw 16)}
  372. GRAFANA_ADMIN_PASSWORD=${GRAFANA_ADMIN_PASSWORD:-$(_rndpw 16)}
  373. GRAYLOG_PASSWORD_SECRET=${GRAYLOG_PASSWORD_SECRET:-$(_rndpw 96)}
  374. GRAYLOG_ROOT_PASSWORD_SHA2=$(echo -n "admin" | sha256sum | cut -d" " -f1)
  375. MAIL_MYSQL_ROOT_PASSWORD=${MAIL_MYSQL_ROOT_PASSWORD:-$(_rndpw 32)}
  376. MAIL_MYSQL_PASSWORD2=${MAIL_MYSQL_PASSWORD:-$(_rndpw 32)}
  377. NEXTCLOUD_MYSQL_ROOT_PASSWORD=${NEXTCLOUD_MYSQL_ROOT_PASSWORD:-$(_rndpw 32)}
  378. NEXTCLOUD_MYSQL_PASSWORD2=${NEXTCLOUD_MYSQL_PASSWORD:-$(_rndpw 32)}
  379. PHPMYADMIN_PASSWORD=${PHPMYADMIN_PASSWORD:-$(_rndpw 16)}
  380. WEBMIN_ROOT_PASSWORD=${WEBMIN_ROOT_PASSWORD:-$(_rndpw 16)}
  381. SMTP_PASSWORD=${SMTP_PASSWORD:-$(_rndpw 32)}
  382. # IP LAN et passerelle du boitier (pour onboarding/diagnostics)
  383. WAOUW_LAN_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.*src \([0-9.]*\).*/\1/p' | head -1 || echo "")
  384. WAOUW_GATEWAY_IP=$(ip route 2>/dev/null | awk '/default/ {print $3; exit}' || echo "")
  385. # Create .env file
  386. sudo tee "$WAOUW_HOME/.env" > /dev/null <<EOF
  387. # WaouW v2.0 COMPLETE Environment Configuration
  388. # Generated on $(date)
  389. # =============================================================================
  390. # DOMAIN & TLS
  391. # =============================================================================
  392. WAOUW_DOMAIN=waouw.local
  393. ACME_EMAIL=ssl-agent@waouw.tech
  394. # =============================================================================
  395. # RESEAU (IP LAN boitier, passerelle - pour onboarding)
  396. # =============================================================================
  397. WAOUW_LAN_IP=$WAOUW_LAN_IP
  398. WAOUW_GATEWAY_IP=$WAOUW_GATEWAY_IP
  399. # =============================================================================
  400. # CORE DATABASE
  401. # =============================================================================
  402. POSTGRES_PASSWORD=$DB_PASSWORD
  403. DATABASE_URL=postgresql://waouw:$DB_PASSWORD@postgres:5432/waouw
  404. # =============================================================================
  405. # CACHE
  406. # =============================================================================
  407. REDIS_URL=redis://redis:6379/0
  408. # =============================================================================
  409. # SECURITY
  410. # =============================================================================
  411. JWT_SECRET_KEY=$JWT_SECRET
  412. DEVICE_HMAC_SECRET=$DEVICE_SECRET
  413. # =============================================================================
  414. # LICENCE / ACTIVATION (waouw-admin online)
  415. # =============================================================================
  416. WAOUW_ADMIN_URL=${WAOUW_ADMIN_URL:-https://admin.waouw.eu}
  417. # =============================================================================
  418. # EMAIL SERVICES
  419. # =============================================================================
  420. MAIL_MYSQL_ROOT_PASSWORD=$MAIL_MYSQL_ROOT_PASSWORD
  421. MAIL_MYSQL_PASSWORD=$MAIL_DB_PASSWORD
  422. SMTP_HOST=postfix
  423. SMTP_PORT=587
  424. SMTP_USERNAME=waouw@waouw.local
  425. SMTP_PASSWORD=$SMTP_PASSWORD
  426. # =============================================================================
  427. # NEXTCLOUD CLOUD
  428. # =============================================================================
  429. NEXTCLOUD_MYSQL_ROOT_PASSWORD=$NEXTCLOUD_MYSQL_ROOT_PASSWORD
  430. NEXTCLOUD_MYSQL_PASSWORD=$NEXTCLOUD_MYSQL_PASSWORD2
  431. NEXTCLOUD_ADMIN_PASSWORD=$NEXTCLOUD_ADMIN_PASSWORD
  432. # =============================================================================
  433. # SYSTEM MANAGEMENT
  434. # =============================================================================
  435. PHPMYADMIN_PASSWORD=$PHPMYADMIN_PASSWORD
  436. WEBMIN_ROOT_PASSWORD=$WEBMIN_ROOT_PASSWORD
  437. # =============================================================================
  438. # SECURITY & VPN
  439. # =============================================================================
  440. F2B_MAXRETRY=5
  441. F2B_BANTIME=3600
  442. F2B_FINDTIME=600
  443. VPN_NETWORK=10.8.0.0/24
  444. VPN_CLIENT_NETWORK=192.168.1.0/24
  445. # =============================================================================
  446. # BACKUP & SYNC
  447. # =============================================================================
  448. BACKUP_RETENTION_DAYS=7
  449. BACKUP_SCHEDULE="0 2 * * *"
  450. # =============================================================================
  451. # MONITORING & LOGS
  452. # =============================================================================
  453. GRAYLOG_PASSWORD_SECRET=$GRAYLOG_PASSWORD_SECRET
  454. GRAYLOG_ROOT_PASSWORD_SHA2=$GRAYLOG_ROOT_PASSWORD_SHA2
  455. GRAFANA_ADMIN_PASSWORD=$GRAFANA_ADMIN_PASSWORD
  456. PROMETHEUS_ENABLED=true
  457. GRAFANA_ENABLED=true
  458. OPENSEARCH_ENABLED=true
  459. MONGO_ENABLED=true
  460. LOG_LEVEL=INFO
  461. METRICS_ENABLED=true
  462. METRICS_INTERVAL=30
  463. # =============================================================================
  464. # RESOURCE LIMITS (Raspberry Pi Optimized)
  465. # =============================================================================
  466. POSTGRES_MEMORY_LIMIT=256
  467. REDIS_MEMORY_LIMIT=128
  468. BACKEND_MEMORY_LIMIT=512
  469. NEXTCLOUD_MEMORY_LIMIT=512
  470. # =============================================================================
  471. # BUILD
  472. # =============================================================================
  473. BUILDPLATFORM=linux/arm64
  474. # =============================================================================
  475. # EXTERNAL INTEGRATIONS
  476. # =============================================================================
  477. CENTRAL_AUTH_URL=https://your-central-server.com/api
  478. DEVICE_HEARTBEAT_INTERVAL=30
  479. # =============================================================================
  480. # TIMEZONE
  481. # =============================================================================
  482. TZ=Europe/Paris
  483. # =============================================================================
  484. # DOCKER HOST INTEGRATION
  485. # GID du groupe "docker" sur l'hôte — permet au container backend d'accéder
  486. # au socket Docker (/var/run/docker.sock) pour déployer les sites.
  487. # =============================================================================
  488. DOCKER_GID=$(getent group docker | cut -d: -f3 || echo "985")
  489. EOF
  490. # Set secure permissions
  491. sudo chmod 600 "$WAOUW_HOME/.env"
  492. sudo chown "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME/.env"
  493. # Save passwords for admin
  494. sudo tee "$WAOUW_HOME/PASSWORDS.txt" > /dev/null <<EOF
  495. WaouW v2.0 COMPLETE - Mots de passe générés
  496. ==========================================
  497. Interface Web:
  498. URL: http://waouw.local
  499. Accès admin local: généré par le flux d'onboarding
  500. Activation online: déclenchée pendant l'onboarding depuis le boîtier
  501. Nextcloud:
  502. URL: http://waouw.local/nextcloud
  503. Admin: admin
  504. Password: $NEXTCLOUD_ADMIN_PASSWORD
  505. Grafana:
  506. URL: http://waouw.local/dashboard
  507. Admin: admin
  508. Password: $GRAFANA_ADMIN_PASSWORD
  509. Webmail (Roundcube):
  510. URL: http://waouw.local/webmail
  511. Utilise les comptes email créés
  512. phpMyAdmin:
  513. URL: http://waouw.local/phpmyadmin
  514. User: root
  515. Password: $DB_PASSWORD
  516. Base de données PostgreSQL:
  517. Host: localhost:5432
  518. Database: waouw
  519. User: waouw
  520. Password: $DB_PASSWORD
  521. IMPORTANT: Gardez ce fichier en sécurité et supprimez-le après avoir noté les mots de passe !
  522. EOF
  523. sudo chown "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME/PASSWORDS.txt"
  524. sudo chmod 600 "$WAOUW_HOME/PASSWORDS.txt"
  525. success "Configuration générée"
  526. }
  527. setup_security() {
  528. log "Configuration de la sécurité..."
  529. # Configure UFW firewall
  530. sudo ufw --force reset
  531. sudo ufw default deny incoming
  532. sudo ufw default allow outgoing
  533. sudo ufw allow ssh
  534. sudo ufw allow 80/tcp
  535. sudo ufw allow 443/tcp
  536. sudo ufw allow 7165/tcp
  537. sudo ufw allow 25/tcp # SMTP
  538. sudo ufw allow 587/tcp # SMTP Submission
  539. sudo ufw allow 993/tcp # IMAPS
  540. sudo ufw allow 995/tcp # POP3S
  541. sudo ufw allow 1194/udp # OpenVPN
  542. sudo ufw allow 10000/tcp # Webmin
  543. sudo ufw allow 5353/udp # mDNS (waouw.local)
  544. sudo ufw --force enable
  545. # Configure basic fail2ban
  546. sudo systemctl enable fail2ban
  547. sudo systemctl start fail2ban
  548. success "Sécurité configurée"
  549. }
  550. setup_ssl_certificates() {
  551. log "Configuration des certificats SSL..."
  552. # Generate self-signed certificate for initial setup
  553. if [[ ! -f /etc/waouw/certs/waouw.local.crt ]]; then
  554. sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  555. -keyout /etc/waouw/certs/waouw.local.key \
  556. -out /etc/waouw/certs/waouw.local.crt \
  557. -subj "/C=FR/ST=France/L=Local/O=WaouW/CN=waouw.local"
  558. fi
  559. # Set permissions
  560. sudo chown -R "$WAOUW_USER:$WAOUW_USER" /etc/waouw/certs
  561. sudo chmod 600 /etc/waouw/certs/*.key
  562. sudo chmod 644 /etc/waouw/certs/*.crt
  563. success "Certificats SSL configurés"
  564. }
  565. setup_traefik_config() {
  566. log "Configuration de Traefik..."
  567. # Dossier de configuration Traefik
  568. if [[ ! -d /etc/waouw/traefik ]]; then
  569. sudo mkdir -p /etc/waouw/traefik
  570. fi
  571. # Copier les fichiers Traefik depuis le dossier du script d'installation
  572. if [[ -f "$SCRIPT_DIR/traefik/traefik.yml" ]]; then
  573. sudo cp "$SCRIPT_DIR/traefik/traefik.yml" /etc/waouw/traefik/traefik.yml
  574. else
  575. warn "Fichier traefik/traefik.yml introuvable"
  576. fi
  577. if [[ -f "$SCRIPT_DIR/traefik/dynamic.yml" ]]; then
  578. sudo cp "$SCRIPT_DIR/traefik/dynamic.yml" /etc/waouw/traefik/dynamic.yml
  579. else
  580. warn "Fichier traefik/dynamic.yml introuvable"
  581. fi
  582. # Dossier des certificats ACME
  583. sudo mkdir -p /etc/waouw/traefik/certificates
  584. if [[ ! -f /etc/waouw/traefik/certificates/acme.json ]]; then
  585. echo '{}' | sudo tee /etc/waouw/traefik/certificates/acme.json >/dev/null
  586. sudo chmod 600 /etc/waouw/traefik/certificates/acme.json
  587. fi
  588. success "Traefik configuré"
  589. }
  590. setup_docker_env() {
  591. log "Configuration de l'environnement Docker..."
  592. # Create Docker networks
  593. docker network create traefik 2>/dev/null || true
  594. # Pull base images for better startup time
  595. docker pull traefik:v2.11
  596. docker pull postgres:15-alpine
  597. docker pull redis:7-alpine
  598. docker pull nextcloud:28-apache
  599. docker pull roundcube/roundcubemail:latest-apache
  600. success "Environnement Docker configuré"
  601. }
  602. initialize_openvpn() {
  603. log "Pré-initialisation OpenVPN (PKI/config)..."
  604. local VPN_IMAGE="lunderhage/openvpn-rpi:latest"
  605. local DOMAIN="${WAOUW_DOMAIN:-waouw.local}"
  606. docker volume create waouw_openvpn_data >/dev/null 2>&1 || true
  607. docker volume create waouw_openvpn_config >/dev/null 2>&1 || true
  608. # If already initialized, skip.
  609. if docker run --rm -v waouw_openvpn_data:/etc/openvpn "$VPN_IMAGE" sh -lc "test -f /etc/openvpn/ovpn_env.sh"; then
  610. log "OpenVPN déjà initialisé"
  611. return
  612. fi
  613. if ! docker run --rm -v waouw_openvpn_data:/etc/openvpn "$VPN_IMAGE" ovpn_genconfig -u "udp://${DOMAIN}:1194"; then
  614. warn "ovpn_genconfig a échoué, le toggle VPN pourra retenter l'initialisation"
  615. return
  616. fi
  617. if ! docker run --rm -v waouw_openvpn_data:/etc/openvpn "$VPN_IMAGE" sh -lc "EASYRSA_BATCH=1 ovpn_initpki nopass"; then
  618. warn "ovpn_initpki a échoué, le toggle VPN pourra retenter l'initialisation"
  619. return
  620. fi
  621. success "OpenVPN initialisé"
  622. }
  623. install_systemd_services() {
  624. log "Installation des services systemd..."
  625. # Script de detection reseau (IP LAN, passerelle) - execute a chaque demarrage
  626. sudo tee "$WAOUW_HOME/scripts/waouw-network-detect.sh" > /dev/null <<'SCRIPT'
  627. #!/bin/bash
  628. ENV_FILE="/opt/waouw/.env"
  629. [ ! -f "$ENV_FILE" ] && exit 0
  630. sed -i '/^WAOUW_LAN_IP=/d' "$ENV_FILE"
  631. sed -i '/^WAOUW_GATEWAY_IP=/d' "$ENV_FILE"
  632. LAN=$(hostname -I 2>/dev/null | awk '{print $1}')
  633. GW=$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')
  634. [ -n "$LAN" ] && echo "WAOUW_LAN_IP=$LAN" >> "$ENV_FILE"
  635. [ -n "$GW" ] && echo "WAOUW_GATEWAY_IP=$GW" >> "$ENV_FILE"
  636. SCRIPT
  637. sudo chmod +x "$WAOUW_HOME/scripts/waouw-network-detect.sh"
  638. sudo chown "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME/scripts/waouw-network-detect.sh"
  639. # Create WaouW stack service
  640. sudo tee /etc/systemd/system/waouw-stack.service > /dev/null <<EOF
  641. [Unit]
  642. Description=WaouW v2.0 Complete Stack
  643. Requires=docker.service
  644. After=docker.service network-online.target
  645. [Service]
  646. Type=oneshot
  647. RemainAfterExit=yes
  648. User=$WAOUW_USER
  649. Group=$WAOUW_USER
  650. WorkingDirectory=$WAOUW_HOME/DEPLOY
  651. ExecStartPre=$WAOUW_HOME/scripts/waouw-network-detect.sh
  652. ExecStart=docker compose --profile vpn up -d
  653. ExecStartPost=/bin/sh -c 'sleep 5 && /usr/bin/docker start waouw_frontend 2>/dev/null || true'
  654. ExecStop=docker compose down
  655. TimeoutStartSec=600
  656. [Install]
  657. WantedBy=multi-user.target
  658. EOF
  659. # Create device agent service
  660. sudo tee /etc/systemd/system/waouw-agent.service > /dev/null <<EOF
  661. [Unit]
  662. Description=WaouW Device Agent
  663. After=network.target
  664. [Service]
  665. Type=simple
  666. User=$WAOUW_USER
  667. Group=$WAOUW_USER
  668. WorkingDirectory=$WAOUW_HOME/DEVICE_AGENT
  669. ExecStart=/usr/bin/python3 waouw_agent.py
  670. Restart=always
  671. RestartSec=10
  672. [Install]
  673. WantedBy=multi-user.target
  674. EOF
  675. # Service waouw-hostname: applique le hostname désiré (écrit par le backend dans /etc/waouw/desired_hostname)
  676. # et redémarre avahi-daemon pour que <hostname>.local soit accessible via mDNS.
  677. sudo tee /usr/local/bin/waouw-apply-hostname > /dev/null <<'SCRIPT'
  678. #!/bin/bash
  679. DESIRED_FILE="/etc/waouw/desired_hostname"
  680. [ -f "$DESIRED_FILE" ] || exit 0
  681. HOSTNAME=$(tr -d '[:space:]' < "$DESIRED_FILE")
  682. [ -z "$HOSTNAME" ] && exit 0
  683. CURRENT=$(hostname)
  684. [ "$HOSTNAME" = "$CURRENT" ] && exit 0
  685. echo "waouw-hostname: application du hostname '$HOSTNAME' (ancien: '$CURRENT')"
  686. hostnamectl set-hostname "$HOSTNAME"
  687. # Mettre à jour /etc/hostname
  688. echo "$HOSTNAME" > /etc/hostname
  689. # Mettre à jour /etc/hosts (remplacer l'ancienne entrée 127.0.1.1)
  690. if grep -q "127.0.1.1" /etc/hosts; then
  691. sed -i "s/127\.0\.1\.1\s.*/127.0.1.1\t$HOSTNAME/" /etc/hosts
  692. else
  693. echo "127.0.1.1 $HOSTNAME" >> /etc/hosts
  694. fi
  695. # Redémarrer Avahi pour diffuser le nouveau nom mDNS
  696. systemctl restart avahi-daemon || true
  697. echo "waouw-hostname: hostname '$HOSTNAME' appliqué, avahi redémarré."
  698. SCRIPT
  699. sudo chmod +x /usr/local/bin/waouw-apply-hostname
  700. # Systemd path unit: déclenche waouw-hostname.service dès que /etc/waouw/desired_hostname est créé/modifié
  701. sudo tee /etc/systemd/system/waouw-hostname.path > /dev/null <<'EOF'
  702. [Unit]
  703. Description=Surveillance du fichier desired_hostname WaouW
  704. After=network.target
  705. [Path]
  706. PathCreated=/etc/waouw/desired_hostname
  707. PathModified=/etc/waouw/desired_hostname
  708. Unit=waouw-hostname.service
  709. [Install]
  710. WantedBy=multi-user.target
  711. EOF
  712. sudo tee /etc/systemd/system/waouw-hostname.service > /dev/null <<'EOF'
  713. [Unit]
  714. Description=Appliquer le hostname WaouW depuis /etc/waouw/desired_hostname
  715. After=network.target
  716. [Service]
  717. Type=oneshot
  718. ExecStart=/usr/local/bin/waouw-apply-hostname
  719. EOF
  720. # Service waouw-relay-tunnel: détecte relay_request.json et configure le tunnel WireGuard
  721. sudo cp /opt/waouw/DEPLOY/scripts/waouw-relay-tunnel.sh /opt/waouw/scripts/waouw-relay-tunnel.sh 2>/dev/null || true
  722. sudo chmod +x /opt/waouw/scripts/waouw-relay-tunnel.sh 2>/dev/null || true
  723. sudo tee /etc/systemd/system/waouw-relay-tunnel.path > /dev/null <<'EOF'
  724. [Unit]
  725. Description=Watch for relay tunnel request
  726. [Path]
  727. PathExists=/etc/waouw/relay_request.json
  728. MakeDirectory=yes
  729. [Install]
  730. WantedBy=multi-user.target
  731. EOF
  732. sudo tee /etc/systemd/system/waouw-relay-tunnel.service > /dev/null <<'EOF'
  733. [Unit]
  734. Description=WaouW Relay Tunnel Setup
  735. After=network-online.target docker.service
  736. Wants=network-online.target
  737. [Service]
  738. Type=oneshot
  739. ExecStart=/opt/waouw/scripts/waouw-relay-tunnel.sh
  740. RemainAfterExit=false
  741. StandardOutput=journal
  742. StandardError=journal
  743. [Install]
  744. WantedBy=multi-user.target
  745. EOF
  746. sudo systemctl daemon-reload
  747. sudo systemctl enable waouw-relay-tunnel.path
  748. sudo systemctl start waouw-relay-tunnel.path
  749. # Service waouw-avahi: publie les alias .local des sites via avahi-publish.
  750. # IMPORTANT: /etc/avahi/hosts ne fonctionne pas pour des alias pointant vers la machine locale
  751. # (cela provoque des "Local name collision"). On utilise donc avahi-publish -a -R par alias.
  752. sudo tee /usr/local/bin/waouw-publish-alias > /dev/null <<'SCRIPT'
  753. #!/bin/bash
  754. set -euo pipefail
  755. ALIAS="${1:-}"
  756. [ -z "$ALIAS" ] && exit 1
  757. LAN_IP="$(grep '^WAOUW_LAN_IP=' /opt/waouw/.env 2>/dev/null | cut -d= -f2)"
  758. if [ -z "$LAN_IP" ]; then
  759. LAN_IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
  760. fi
  761. [ -z "$LAN_IP" ] && exit 1
  762. exec /usr/bin/avahi-publish -a -R "$ALIAS" "$LAN_IP"
  763. SCRIPT
  764. sudo chmod +x /usr/local/bin/waouw-publish-alias
  765. sudo tee /usr/local/bin/waouw-sync-avahi-aliases > /dev/null <<'SCRIPT'
  766. #!/bin/bash
  767. set -euo pipefail
  768. HOSTS_SRC="/etc/waouw/avahi-site-hosts"
  769. mapfile -t current_units < <(systemctl list-units --full --all 'waouw-avahi-alias@*.service' --no-legend | awk '{print $1}')
  770. declare -A wanted
  771. if [ -f "$HOSTS_SRC" ]; then
  772. while read -r a b _; do
  773. [ -z "${a:-}" ] && continue
  774. case "$a" in \#*) continue ;; esac
  775. # Support both formats:
  776. # 1) "192.168.1.115 monsite.local"
  777. # 2) "monsite.local"
  778. if echo "$a" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'; then
  779. alias="${b:-}"
  780. else
  781. alias="$a"
  782. fi
  783. alias="$(echo "$alias" | tr '[:upper:]' '[:lower:]' | xargs)"
  784. [ -z "$alias" ] && continue
  785. case "$alias" in
  786. *.local) wanted["$alias"]=1 ;;
  787. *) ;;
  788. esac
  789. done < "$HOSTS_SRC"
  790. fi
  791. # Stop aliases that are no longer present
  792. for unit in "${current_units[@]}"; do
  793. [ -z "$unit" ] && continue
  794. inst="${unit#waouw-avahi-alias@}"
  795. inst="${inst%.service}"
  796. alias="$(systemd-escape --unescape "$inst")"
  797. if [ -z "${wanted[$alias]:-}" ]; then
  798. systemctl stop "$unit" 2>/dev/null || true
  799. systemctl disable "$unit" 2>/dev/null || true
  800. fi
  801. done
  802. # Start/update aliases present in config file
  803. for alias in "${!wanted[@]}"; do
  804. esc="$(systemd-escape "$alias")"
  805. unit="waouw-avahi-alias@${esc}.service"
  806. systemctl enable "$unit" >/dev/null 2>&1 || true
  807. systemctl restart "$unit"
  808. done
  809. echo "waouw-avahi: aliases synchronisés (${#wanted[@]})"
  810. SCRIPT
  811. sudo chmod +x /usr/local/bin/waouw-sync-avahi-aliases
  812. sudo tee /etc/systemd/system/waouw-avahi.path > /dev/null <<'EOF'
  813. [Unit]
  814. Description=Surveillance des domaines locaux WaouW (avahi-site-hosts)
  815. After=avahi-daemon.service
  816. [Path]
  817. PathModified=/etc/waouw/avahi-reload-signal
  818. Unit=waouw-avahi.service
  819. [Install]
  820. WantedBy=multi-user.target
  821. EOF
  822. sudo tee /etc/systemd/system/waouw-avahi.service > /dev/null <<'EOF'
  823. [Unit]
  824. Description=Appliquer les domaines .local WaouW dans Avahi
  825. After=avahi-daemon.service
  826. [Service]
  827. Type=oneshot
  828. ExecStart=/usr/local/bin/waouw-sync-avahi-aliases
  829. EOF
  830. sudo tee /etc/systemd/system/waouw-avahi-alias@.service > /dev/null <<'EOF'
  831. [Unit]
  832. Description=Publier alias mDNS WaouW (%I)
  833. After=network-online.target avahi-daemon.service
  834. Wants=network-online.target avahi-daemon.service
  835. [Service]
  836. Type=simple
  837. ExecStart=/usr/local/bin/waouw-publish-alias %I
  838. Restart=always
  839. RestartSec=2
  840. EOF
  841. # ── vsftpd for per-site FTP access ──────────────────────────────────────
  842. sudo apt-get install -y vsftpd db-util 2>/dev/null || true
  843. sudo useradd -r -d /opt/waouw/sites-data -s /usr/sbin/nologin ftpvirtual 2>/dev/null || true
  844. sudo mkdir -p /etc/vsftpd /opt/waouw/sites-data
  845. sudo touch /etc/vsftpd/virtual_users.txt
  846. sudo tee /etc/vsftpd.conf > /dev/null <<'FTPCONF'
  847. listen=YES
  848. listen_ipv6=NO
  849. anonymous_enable=NO
  850. local_enable=YES
  851. write_enable=YES
  852. local_umask=022
  853. dirmessage_enable=YES
  854. use_localtime=YES
  855. xferlog_enable=YES
  856. connect_from_port_20=YES
  857. chroot_local_user=YES
  858. allow_writeable_chroot=YES
  859. guest_enable=YES
  860. guest_username=ftpvirtual
  861. user_sub_token=$USER
  862. local_root=/opt/waouw/sites-data/$USER/html
  863. virtual_use_local_privs=YES
  864. pam_service_name=vsftpd.virtual
  865. hide_ids=YES
  866. pasv_enable=YES
  867. pasv_min_port=30000
  868. pasv_max_port=30009
  869. seccomp_sandbox=NO
  870. FTPCONF
  871. sudo tee /etc/pam.d/vsftpd.virtual > /dev/null <<'FTPPAM'
  872. auth required pam_userdb.so db=/etc/vsftpd/virtual_users
  873. account required pam_userdb.so db=/etc/vsftpd/virtual_users
  874. FTPPAM
  875. # Script: process FTP user requests written by backend
  876. sudo tee /usr/local/bin/waouw-sync-ftp-users > /dev/null <<'FTPSCRIPT'
  877. #!/bin/bash
  878. set -eo pipefail
  879. PENDING="/etc/waouw/ftp-pending"
  880. VFILE="/etc/vsftpd/virtual_users.txt"
  881. DB="/etc/vsftpd/virtual_users"
  882. shopt -s nullglob
  883. files=("$PENDING"/*)
  884. [ ${#files[@]} -eq 0 ] && exit 0
  885. for f in "${files[@]}"; do
  886. slug=$(basename "$f")
  887. pass=$(cat "$f")
  888. [ -z "$slug" ] && continue
  889. mkdir -p "/opt/waouw/sites-data/$slug/html"
  890. chown -R ftpvirtual:ftpvirtual "/opt/waouw/sites-data/$slug"
  891. chmod 775 "/opt/waouw/sites-data/$slug/html"
  892. # Remove old entry if exists, then add
  893. grep -v "^${slug}$" "$VFILE" > "${VFILE}.tmp" 2>/dev/null || true
  894. mv "${VFILE}.tmp" "$VFILE"
  895. echo "$slug" >> "$VFILE"
  896. echo "$pass" >> "$VFILE"
  897. rm -f "$f"
  898. done
  899. db_load -T -t hash -f "$VFILE" "${DB}.db" 2>/dev/null || true
  900. systemctl reload vsftpd 2>/dev/null || systemctl restart vsftpd 2>/dev/null || true
  901. echo "waouw-ftp: $(( ${#files[@]} )) utilisateurs traités"
  902. FTPSCRIPT
  903. sudo chmod +x /usr/local/bin/waouw-sync-ftp-users
  904. # Systemd path unit to watch FTP pending directory
  905. sudo tee /etc/systemd/system/waouw-ftp.path > /dev/null <<'EOF'
  906. [Unit]
  907. Description=Surveillance des demandes FTP WaouW
  908. [Path]
  909. PathModified=/etc/waouw/ftp-pending
  910. Unit=waouw-ftp.service
  911. [Install]
  912. WantedBy=multi-user.target
  913. EOF
  914. sudo tee /etc/systemd/system/waouw-ftp.service > /dev/null <<'EOF'
  915. [Unit]
  916. Description=Traitement des comptes FTP WaouW
  917. [Service]
  918. Type=oneshot
  919. ExecStart=/usr/local/bin/waouw-sync-ftp-users
  920. EOF
  921. sudo systemctl enable vsftpd 2>/dev/null || true
  922. sudo systemctl start vsftpd 2>/dev/null || true
  923. # ── Headless: couper HDMI / consoles locales après boot (sauf si marqueur boot présent)
  924. sudo tee /usr/local/bin/waouw-disable-local-console > /dev/null <<'SCRIPT'
  925. #!/bin/bash
  926. for mark in /boot/firmware/waouw-show-console /boot/waouw-show-console; do
  927. if [ -f "$mark" ]; then
  928. logger -t waouw-headless "Marqueur $mark présent: affichage local conservé."
  929. exit 0
  930. fi
  931. done
  932. if command -v vcgencmd >/dev/null 2>&1; then
  933. vcgencmd display_power 0 2>/dev/null || true
  934. fi
  935. for n in 1 2 3 4 5 6; do
  936. TTY="/dev/tty$n"
  937. if [ -c "$TTY" ]; then
  938. setterm --blank force --powerdown 3 <"$TTY" >"$TTY" 2>/dev/null || true
  939. fi
  940. done
  941. logger -t waouw-headless "Sorties écran locales atténuées (HDMI / TTY)."
  942. exit 0
  943. SCRIPT
  944. sudo chmod +x /usr/local/bin/waouw-disable-local-console
  945. sudo tee /etc/systemd/system/waouw-headless-display.service > /dev/null <<'EOF'
  946. [Unit]
  947. Description=WaouW — réduire les sorties écran locales (headless)
  948. After=multi-user.target
  949. [Service]
  950. Type=oneshot
  951. ExecStart=/usr/local/bin/waouw-disable-local-console
  952. RemainAfterExit=yes
  953. [Install]
  954. WantedBy=multi-user.target
  955. EOF
  956. sudo tee /usr/local/bin/waouw-apply-support-ssh > /dev/null <<'SCRIPT'
  957. #!/bin/bash
  958. set -euo pipefail
  959. PENDING="/etc/waouw/pending_support_ssh.json"
  960. [ -f "$PENDING" ] || exit 0
  961. python3 <<'PY'
  962. import json
  963. import os
  964. import subprocess
  965. import sys
  966. path = "/etc/waouw/pending_support_ssh.json"
  967. try:
  968. with open(path, "r", encoding="utf-8") as f:
  969. data = json.load(f)
  970. except Exception:
  971. try:
  972. os.unlink(path)
  973. except OSError:
  974. pass
  975. sys.exit(0)
  976. user = str(data.get("user") or "waouw").strip()
  977. password = str(data.get("password") or "")
  978. if user not in ("waouw", "root") or not password or len(password) > 512:
  979. try:
  980. os.unlink(path)
  981. except OSError:
  982. pass
  983. sys.exit(1)
  984. try:
  985. subprocess.run(
  986. ["/usr/sbin/chpasswd"],
  987. input=f"{user}:{password}\n".encode("utf-8"),
  988. check=True,
  989. timeout=30,
  990. )
  991. except Exception:
  992. sys.exit(1)
  993. try:
  994. os.unlink(path)
  995. except OSError:
  996. pass
  997. print("waouw-support-ssh: mot de passe appliqué pour", user, file=sys.stderr)
  998. PY
  999. SCRIPT
  1000. sudo chmod +x /usr/local/bin/waouw-apply-support-ssh
  1001. sudo tee /etc/systemd/system/waouw-support-ssh.path > /dev/null <<'EOF'
  1002. [Unit]
  1003. Description=Surveiller demande de rotation mot de passe SSH support WaouW
  1004. After=network.target
  1005. [Path]
  1006. PathModified=/etc/waouw/pending_support_ssh.json
  1007. PathCreated=/etc/waouw/pending_support_ssh.json
  1008. Unit=waouw-support-ssh.service
  1009. [Install]
  1010. WantedBy=multi-user.target
  1011. EOF
  1012. sudo tee /etc/systemd/system/waouw-support-ssh.service > /dev/null <<'EOF'
  1013. [Unit]
  1014. Description=Appliquer rotation mot de passe SSH support (WaouW)
  1015. After=network.target
  1016. [Service]
  1017. Type=oneshot
  1018. ExecStart=/usr/local/bin/waouw-apply-support-ssh
  1019. EOF
  1020. # Reload systemd and enable services
  1021. sudo systemctl daemon-reload
  1022. sudo systemctl enable waouw-stack.service
  1023. sudo systemctl enable waouw-agent.service
  1024. sudo systemctl enable waouw-hostname.path
  1025. sudo systemctl start waouw-hostname.path 2>/dev/null || true
  1026. sudo systemctl enable waouw-avahi.path
  1027. sudo systemctl start waouw-avahi.path 2>/dev/null || true
  1028. sudo systemctl enable waouw-ftp.path
  1029. sudo systemctl start waouw-ftp.path 2>/dev/null || true
  1030. sudo systemctl enable waouw-headless-display.service
  1031. sudo systemctl start waouw-headless-display.service 2>/dev/null || true
  1032. sudo systemctl enable waouw-support-ssh.path
  1033. sudo systemctl start waouw-support-ssh.path 2>/dev/null || true
  1034. # Handler rotation JWT_SECRET_KEY (déclenchée par l'onboarding au 1er lancement).
  1035. # Même pattern que support-ssh : un fichier pending écrit par le backend, un
  1036. # path unit systemd l'intercepte, un script host applique la rotation.
  1037. sudo tee /usr/local/bin/waouw-apply-jwt-rotation > /dev/null <<'SCRIPT'
  1038. #!/bin/bash
  1039. set -euo pipefail
  1040. PENDING="/etc/waouw/pending_jwt_rotation.json"
  1041. SENTINEL="/etc/waouw/jwt_rotated"
  1042. ENV_FILE="/opt/waouw/.env"
  1043. [ -f "$PENDING" ] || exit 0
  1044. [ -f "$ENV_FILE" ] || { rm -f "$PENDING"; exit 1; }
  1045. NEW_JWT=$(python3 -c "import json,sys; print(json.load(open('$PENDING'))['jwt_secret_key'])" 2>/dev/null || true)
  1046. if [ -z "$NEW_JWT" ] || [ ${#NEW_JWT} -lt 32 ]; then
  1047. rm -f "$PENDING"
  1048. exit 1
  1049. fi
  1050. # Remplacer ou ajouter JWT_SECRET_KEY dans /opt/waouw/.env
  1051. if grep -q '^JWT_SECRET_KEY=' "$ENV_FILE"; then
  1052. sed -i "s|^JWT_SECRET_KEY=.*|JWT_SECRET_KEY=$NEW_JWT|" "$ENV_FILE"
  1053. else
  1054. echo "JWT_SECRET_KEY=$NEW_JWT" >> "$ENV_FILE"
  1055. fi
  1056. # Marquer comme rotaté AVANT le restart (sinon le backend qui redémarre
  1057. # réécrit un pending et boucle).
  1058. touch "$SENTINEL"
  1059. rm -f "$PENDING"
  1060. # Redémarrer backend + worker pour prendre en compte le nouveau secret.
  1061. cd /opt/waouw/DEPLOY 2>/dev/null && docker compose restart backend worker 2>&1 | tail -5 || true
  1062. echo "waouw-jwt-rotation: JWT_SECRET_KEY rotaté + backend/worker redémarrés" >&2
  1063. SCRIPT
  1064. sudo chmod +x /usr/local/bin/waouw-apply-jwt-rotation
  1065. sudo tee /etc/systemd/system/waouw-jwt-rotation.path > /dev/null <<'EOF'
  1066. [Unit]
  1067. Description=Surveiller demande de rotation JWT_SECRET_KEY WaouW
  1068. After=network.target
  1069. [Path]
  1070. PathModified=/etc/waouw/pending_jwt_rotation.json
  1071. PathCreated=/etc/waouw/pending_jwt_rotation.json
  1072. Unit=waouw-jwt-rotation.service
  1073. [Install]
  1074. WantedBy=multi-user.target
  1075. EOF
  1076. sudo tee /etc/systemd/system/waouw-jwt-rotation.service > /dev/null <<'EOF'
  1077. [Unit]
  1078. Description=Appliquer rotation JWT_SECRET_KEY (WaouW)
  1079. After=network.target docker.service
  1080. [Service]
  1081. Type=oneshot
  1082. ExecStart=/usr/local/bin/waouw-apply-jwt-rotation
  1083. EOF
  1084. sudo systemctl enable waouw-jwt-rotation.path
  1085. sudo systemctl start waouw-jwt-rotation.path 2>/dev/null || true
  1086. success "Services systemd installés"
  1087. }
  1088. deploy_services() {
  1089. log "Déploiement des services..."
  1090. cd "$SCRIPT_DIR"
  1091. # Rendre le .env accessible à docker compose depuis ce dossier
  1092. if [ -f "$WAOUW_HOME/.env" ] && [ ! -f "$SCRIPT_DIR/.env" ]; then
  1093. ln -sf "$WAOUW_HOME/.env" "$SCRIPT_DIR/.env"
  1094. fi
  1095. # S'assurer que le script de detection reseau existe (installations existantes)
  1096. if [ ! -x "$WAOUW_HOME/scripts/waouw-network-detect.sh" ]; then
  1097. sudo tee "$WAOUW_HOME/scripts/waouw-network-detect.sh" > /dev/null <<'SCRIPT'
  1098. #!/bin/bash
  1099. ENV_FILE="/opt/waouw/.env"
  1100. [ ! -f "$ENV_FILE" ] && exit 0
  1101. sed -i '/^WAOUW_LAN_IP=/d' "$ENV_FILE"
  1102. sed -i '/^WAOUW_GATEWAY_IP=/d' "$ENV_FILE"
  1103. LAN=$(hostname -I 2>/dev/null | awk '{print $1}')
  1104. GW=$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')
  1105. [ -n "$LAN" ] && echo "WAOUW_LAN_IP=$LAN" >> "$ENV_FILE"
  1106. [ -n "$GW" ] && echo "WAOUW_GATEWAY_IP=$GW" >> "$ENV_FILE"
  1107. SCRIPT
  1108. sudo chmod +x "$WAOUW_HOME/scripts/waouw-network-detect.sh"
  1109. sudo chown "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME/scripts/waouw-network-detect.sh"
  1110. fi
  1111. # Mettre à jour waouw-stack pour ExecStartPre si absent (détection à chaque démarrage)
  1112. if [ -f /etc/systemd/system/waouw-stack.service ] && ! grep -q 'ExecStartPre=.*waouw-network-detect' /etc/systemd/system/waouw-stack.service 2>/dev/null; then
  1113. sudo sed -i "/^ExecStart=docker compose/i ExecStartPre=$WAOUW_HOME/scripts/waouw-network-detect.sh" /etc/systemd/system/waouw-stack.service
  1114. sudo systemctl daemon-reload
  1115. fi
  1116. # Détection reseau avant docker compose (à chaque déploiement)
  1117. "$WAOUW_HOME/scripts/waouw-network-detect.sh" 2>/dev/null || true
  1118. # Pull des images avec retry (le réseau WiFi du Pi peut être instable)
  1119. local max_retries=5
  1120. local retry_delay=15
  1121. for attempt in $(seq 1 $max_retries); do
  1122. log "Pull des images Docker (tentative $attempt/$max_retries)..."
  1123. if docker compose pull 2>&1; then
  1124. log "Pull des images réussi"
  1125. break
  1126. fi
  1127. if [ "$attempt" -eq "$max_retries" ]; then
  1128. warn "Pull échoué après $max_retries tentatives, on tente le up quand même..."
  1129. else
  1130. log "Pull échoué, nouvelle tentative dans ${retry_delay}s..."
  1131. sleep $retry_delay
  1132. retry_delay=$((retry_delay * 2))
  1133. fi
  1134. done
  1135. # Lancement des services avec retry
  1136. local up_retries=3
  1137. local up_delay=20
  1138. for attempt in $(seq 1 $up_retries); do
  1139. log "Lancement des services (tentative $attempt/$up_retries)..."
  1140. if docker compose --profile vpn up -d --build 2>&1; then
  1141. break
  1142. fi
  1143. if [ "$attempt" -eq "$up_retries" ]; then
  1144. error "docker compose up échoué après $up_retries tentatives"
  1145. return 1
  1146. fi
  1147. log "Lancement échoué, nouvelle tentative dans ${up_delay}s..."
  1148. sleep $up_delay
  1149. up_delay=$((up_delay * 2))
  1150. done
  1151. # Wait for services to be ready
  1152. log "Attente du démarrage des services..."
  1153. sleep 30
  1154. # Check services status
  1155. docker compose ps
  1156. success "Services déployés"
  1157. }
  1158. verify_local_web_access() {
  1159. log "Validation finale de l'interface locale..."
  1160. local root_code=""
  1161. local onboarding_code=""
  1162. local attempt=1
  1163. local max_attempts=24
  1164. while [[ $attempt -le $max_attempts ]]; do
  1165. root_code=$(curl -sk -o /dev/null -w "%{http_code}" -L http://127.0.0.1/ || true)
  1166. onboarding_code=$(curl -sk -o /dev/null -w "%{http_code}" -L http://127.0.0.1/api/v1/onboarding/status || true)
  1167. if [[ "$root_code" == "200" && "$onboarding_code" == "200" ]]; then
  1168. success "Interface locale validée (/, /api/v1/onboarding/status)"
  1169. return 0
  1170. fi
  1171. log "Interface locale pas encore prête (tentative $attempt/$max_attempts, /=$root_code, onboarding=$onboarding_code)"
  1172. sleep 5
  1173. attempt=$((attempt + 1))
  1174. done
  1175. error "Validation finale échouée: interface locale indisponible ou incorrecte (/, /api/v1/onboarding/status)"
  1176. docker compose ps || true
  1177. return 1
  1178. }
  1179. setup_device_agent() {
  1180. log "Configuration de l'agent device..."
  1181. # Install Python dependencies for agent
  1182. sudo DEBIAN_FRONTEND=noninteractive apt-get install -y python3-pip python3-venv
  1183. # Create virtual environment for agent
  1184. cd "$WAOUW_HOME/DEVICE_AGENT"
  1185. sudo -u "$WAOUW_USER" python3 -m venv venv
  1186. if [ -f requirements.txt ]; then
  1187. sudo -u "$WAOUW_USER" ./venv/bin/pip install -r requirements.txt
  1188. else
  1189. warn "requirements.txt absent pour DEVICE_AGENT, installation des dépendances minimales"
  1190. sudo -u "$WAOUW_USER" ./venv/bin/pip install aiohttp psutil
  1191. fi
  1192. # Start agent service
  1193. sudo systemctl start waouw-agent.service
  1194. success "Agent device configuré"
  1195. }
  1196. setup_monitoring() {
  1197. log "Configuration du monitoring..."
  1198. # Configure log rotation
  1199. sudo tee /etc/logrotate.d/waouw > /dev/null <<EOF
  1200. /var/log/waouw/*.log {
  1201. daily
  1202. missingok
  1203. rotate 7
  1204. compress
  1205. delaycompress
  1206. notifempty
  1207. create 644 $WAOUW_USER $WAOUW_USER
  1208. }
  1209. EOF
  1210. success "Monitoring configuré"
  1211. }
  1212. setup_luks_infrastructure() {
  1213. log "Installation de l'infrastructure de chiffrement LUKS..."
  1214. # Install cryptsetup-initramfs
  1215. DEBIAN_FRONTEND=noninteractive apt-get install -y cryptsetup cryptsetup-initramfs 2>/dev/null || true
  1216. # Copy initramfs hook
  1217. if [ -f "$WAOUW_HOME/DEPLOY/initramfs/hooks/waouw-cryptroot" ]; then
  1218. sudo cp -f "$WAOUW_HOME/DEPLOY/initramfs/hooks/waouw-cryptroot" /etc/initramfs-tools/hooks/waouw-cryptroot
  1219. sudo chmod +x /etc/initramfs-tools/hooks/waouw-cryptroot
  1220. fi
  1221. # Copy keyscript
  1222. mkdir -p /etc/waouw /usr/lib/cryptsetup/scripts
  1223. if [ -f "$WAOUW_HOME/DEPLOY/initramfs/scripts/waouw-keyfetch" ]; then
  1224. sudo cp -f "$WAOUW_HOME/DEPLOY/initramfs/scripts/waouw-keyfetch" /usr/lib/cryptsetup/scripts/waouw-keyfetch
  1225. sudo chmod +x /usr/lib/cryptsetup/scripts/waouw-keyfetch
  1226. sudo cp -f "$WAOUW_HOME/DEPLOY/initramfs/scripts/waouw-keyfetch" /etc/waouw/waouw-keyfetch
  1227. sudo chmod +x /etc/waouw/waouw-keyfetch
  1228. fi
  1229. # Add required kernel modules for initramfs
  1230. cat > /etc/initramfs-tools/modules <<'MODULES'
  1231. # Network — Ethernet Pi 4
  1232. bcmgenet
  1233. mdio_bcm_unimac
  1234. # Network — WiFi Pi 4/5
  1235. brcmfmac
  1236. brcmutil
  1237. cfg80211
  1238. rfkill
  1239. # Crypto
  1240. dm_crypt
  1241. aes_ce_blk
  1242. aes_arm64
  1243. sha256_ce
  1244. MODULES
  1245. # Save device ID to boot partition
  1246. BOOT_MOUNT="/boot/firmware"
  1247. [ -d "$BOOT_MOUNT" ] || BOOT_MOUNT="/boot"
  1248. DEVICE_ID=""
  1249. [ -f /etc/waouw/device_id ] && DEVICE_ID=$(cat /etc/waouw/device_id)
  1250. if [ -n "$DEVICE_ID" ]; then
  1251. echo "$DEVICE_ID" > "${BOOT_MOUNT}/waouw-device-id"
  1252. fi
  1253. # If root is LUKS (encrypted by initramfs at boot), configure and re-key
  1254. ROOT_DEV="/dev/mmcblk0p2"
  1255. CRYPT_NAME="cryptroot"
  1256. if cryptsetup isLuks "$ROOT_DEV" 2>/dev/null; then
  1257. log "Root is LUKS encrypted — configuring system"
  1258. # Configure crypttab
  1259. echo "$CRYPT_NAME $ROOT_DEV none luks,initramfs,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" > /etc/crypttab
  1260. # Re-key: replace lot key with a unique device key
  1261. LOT_FILE="${BOOT_MOUNT}/.waouw-lot-id"
  1262. ADMIN_URL_FILE="${BOOT_MOUNT}/waouw-admin-url.txt"
  1263. ADMIN_URL=""
  1264. [ -f "$ADMIN_URL_FILE" ] && ADMIN_URL=$(cat "$ADMIN_URL_FILE" 2>/dev/null | tr -d '\r\n ')
  1265. if [ -f "$LOT_FILE" ] && [ -n "$ADMIN_URL" ]; then
  1266. log "Re-keying: replacing lot key with unique device key..."
  1267. LOT_ID=$(cat "$LOT_FILE" 2>/dev/null | tr -d '\r\n ')
  1268. SERIAL=$(grep -oP 'Serial\s*:\s*0*\K[0-9a-f]+' /proc/cpuinfo 2>/dev/null || echo "")
  1269. [ -z "$DEVICE_ID" ] && DEVICE_ID="$SERIAL"
  1270. if [ -n "$LOT_ID" ] && [ -n "$SERIAL" ]; then
  1271. # Get the lot key
  1272. TIMESTAMP=$(date +%s)
  1273. BOOT_SECRET=$(echo -n "${LOT_ID}waouw-boot-2026" | sha256sum | cut -d' ' -f1)
  1274. HMAC=$(echo -n "${TIMESTAMP}${LOT_ID}" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$BOOT_SECRET" -hex 2>/dev/null | awk '{print $NF}')
  1275. LOT_RESP=$(curl -sf --max-time 30 \
  1276. -X POST -H "Content-Type: application/json" \
  1277. -H "X-Waouw-Boot-Hmac: ${HMAC}" \
  1278. -H "X-Waouw-Timestamp: ${TIMESTAMP}" \
  1279. -d "{\"action\":\"retrieve_lot\",\"lot_id\":\"${LOT_ID}\"}" \
  1280. "${ADMIN_URL}/api/device_luks_key.php" 2>/dev/null) || true
  1281. OLD_KEY=$(echo "$LOT_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('luks_key',''))" 2>/dev/null || echo "")
  1282. if [ -n "$OLD_KEY" ] && [ ${#OLD_KEY} -ge 32 ]; then
  1283. # Generate unique device key
  1284. NEW_KEY=$(openssl rand -hex 32)
  1285. # Add new key, remove old key
  1286. echo -n "$OLD_KEY" | cryptsetup luksAddKey --key-file=- "$ROOT_DEV" <(echo -n "$NEW_KEY") 2>&1 || {
  1287. log "WARNING: luksAddKey failed, keeping lot key"
  1288. NEW_KEY=""
  1289. }
  1290. if [ -n "$NEW_KEY" ]; then
  1291. echo -n "$OLD_KEY" | cryptsetup luksRemoveKey --key-file=- "$ROOT_DEV" 2>&1 || {
  1292. log "WARNING: luksRemoveKey failed, both keys active"
  1293. }
  1294. # Register new key on waouw-admin
  1295. TIMESTAMP=$(date +%s)
  1296. BOOT_SECRET=$(echo -n "${SERIAL}waouw-boot-2026" | sha256sum | cut -d' ' -f1)
  1297. HMAC=$(echo -n "${TIMESTAMP}${SERIAL}" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$BOOT_SECRET" -hex 2>/dev/null | awk '{print $NF}')
  1298. REG_RESP=$(curl -sf --max-time 30 \
  1299. -X POST -H "Content-Type: application/json" \
  1300. -H "X-Waouw-Boot-Hmac: ${HMAC}" \
  1301. -H "X-Waouw-Timestamp: ${TIMESTAMP}" \
  1302. -d "{\"action\":\"register\",\"serial\":\"${SERIAL}\",\"device_id\":\"${DEVICE_ID}\",\"luks_key\":\"${NEW_KEY}\"}" \
  1303. "${ADMIN_URL}/api/device_luks_key.php" 2>/dev/null) || true
  1304. if echo "$REG_RESP" | grep -q '"ok":true'; then
  1305. log "Device key registered on waouw-admin"
  1306. # Remove lot ID — this device now has its own key
  1307. rm -f "$LOT_FILE"
  1308. log "Lot ID removed from boot partition"
  1309. else
  1310. log "WARNING: Could not register device key on waouw-admin: $REG_RESP"
  1311. fi
  1312. unset NEW_KEY OLD_KEY
  1313. fi
  1314. else
  1315. log "WARNING: Could not retrieve lot key, skipping re-key"
  1316. fi
  1317. fi
  1318. fi
  1319. # Rebuild initramfs with hooks
  1320. update-initramfs -u -k all 2>&1 | tail -5
  1321. success "Infrastructure LUKS configurée + re-keyed"
  1322. else
  1323. log "Root non chiffré — infrastructure LUKS pré-installée"
  1324. update-initramfs -u -k all 2>&1 | tail -3 || true
  1325. success "Infrastructure LUKS pré-installée"
  1326. fi
  1327. }
  1328. final_configuration() {
  1329. log "Configuration finale du système..."
  1330. # Configure system limits for containers
  1331. echo "$WAOUW_USER soft nofile 65536" | sudo tee -a /etc/security/limits.conf
  1332. echo "$WAOUW_USER hard nofile 65536" | sudo tee -a /etc/security/limits.conf
  1333. # Configure kernel parameters for better performance
  1334. echo "net.core.somaxconn = 1024" | sudo tee -a /etc/sysctl.conf
  1335. echo "vm.overcommit_memory = 1" | sudo tee -a /etc/sysctl.conf
  1336. sudo sysctl -p
  1337. # Create WaouW service status script
  1338. sudo tee /usr/local/bin/waouw-status > /dev/null <<'EOF'
  1339. #!/bin/bash
  1340. echo "=== WaouW v2.0 COMPLETE Status ==="
  1341. echo ""
  1342. echo "🐳 Core Services:"
  1343. docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep waouw
  1344. echo ""
  1345. echo "📊 System Resources:"
  1346. echo "CPU: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)%"
  1347. echo "Memory: $(free -h | awk '/^Mem:/ {print $3"/"$2}')"
  1348. echo "Disk: $(df -h / | awk 'NR==2 {print $3"/"$2" ("$5")"}')"
  1349. if [[ -f /sys/class/thermal/thermal_zone0/temp ]]; then
  1350. temp=$(cat /sys/class/thermal/thermal_zone0/temp)
  1351. echo "Temperature: $((temp/1000))°C"
  1352. fi
  1353. echo ""
  1354. echo "🌐 Network:"
  1355. ip -4 addr show | grep inet | grep -v 127.0.0.1
  1356. echo ""
  1357. echo "🔥 Firewall Status:"
  1358. sudo ufw status | head -5
  1359. echo ""
  1360. echo "📧 Email Services:"
  1361. systemctl is-active postfix dovecot 2>/dev/null | xargs echo "Postfix/Dovecot:"
  1362. echo ""
  1363. echo "🛡️ Security Services:"
  1364. systemctl is-active fail2ban 2>/dev/null | xargs echo "Fail2ban:"
  1365. EOF
  1366. sudo chmod +x /usr/local/bin/waouw-status
  1367. # Create WaouW quick commands
  1368. sudo tee /usr/local/bin/waouw > /dev/null <<EOF
  1369. #!/bin/bash
  1370. case "\$1" in
  1371. status)
  1372. waouw-status
  1373. ;;
  1374. logs)
  1375. cd $WAOUW_HOME/DEPLOY && docker compose logs -f
  1376. ;;
  1377. restart)
  1378. systemctl restart waouw-stack
  1379. ;;
  1380. stop)
  1381. systemctl stop waouw-stack
  1382. ;;
  1383. start)
  1384. systemctl start waouw-stack
  1385. ;;
  1386. update)
  1387. cd $WAOUW_HOME && git pull
  1388. [ -x $WAOUW_HOME/scripts/waouw-network-detect.sh ] && $WAOUW_HOME/scripts/waouw-network-detect.sh
  1389. cd $WAOUW_HOME/DEPLOY && docker compose --profile vpn up -d --build
  1390. ;;
  1391. backup)
  1392. $WAOUW_HOME/scripts/backup.sh
  1393. ;;
  1394. passwords)
  1395. cat $WAOUW_HOME/PASSWORDS.txt
  1396. ;;
  1397. *)
  1398. echo "Usage: waouw {status|logs|restart|stop|start|update|backup|passwords}"
  1399. exit 1
  1400. ;;
  1401. esac
  1402. EOF
  1403. sudo chmod +x /usr/local/bin/waouw
  1404. success "Configuration finale terminée"
  1405. }
  1406. disable_pi_user() {
  1407. log "Désactivation de l'utilisateur pi..."
  1408. if id -u pi >/dev/null 2>&1; then
  1409. sudo usermod --expiredate 1 pi || true
  1410. sudo usermod -L pi || true
  1411. sudo passwd -l pi || true
  1412. # Remplacer le shell par nologin pour sécurité
  1413. if getent shells | grep -q "/usr/sbin/nologin"; then
  1414. sudo chsh -s /usr/sbin/nologin pi || true
  1415. fi
  1416. success "Utilisateur pi désactivé"
  1417. else
  1418. warn "Utilisateur pi introuvable (déjà désactivé ou supprimé)"
  1419. fi
  1420. }
  1421. install_waouw() {
  1422. log "Installation de WaouW v2.0 COMPLETE..."
  1423. touch /boot/.waouwinit
  1424. create_waouw_user
  1425. create_directories
  1426. install_activation_bootstrap
  1427. ensure_device_runtime_files
  1428. copy_waouw_files
  1429. generate_config
  1430. install_system_dependencies
  1431. setup_security
  1432. setup_ssl_certificates
  1433. setup_traefik_config
  1434. setup_docker_env
  1435. initialize_openvpn
  1436. install_systemd_services
  1437. # Libérer le port 25 si Postfix hôte est installé (le mail passe par le conteneur Docker)
  1438. if systemctl is-active --quiet postfix 2>/dev/null; then
  1439. log "Arrêt de Postfix hôte (port 25 réservé au conteneur Docker)..."
  1440. sudo systemctl stop postfix
  1441. sudo systemctl disable postfix
  1442. fi
  1443. deploy_services
  1444. verify_local_web_access
  1445. setup_device_agent
  1446. setup_monitoring
  1447. disable_pi_user
  1448. setup_luks_infrastructure
  1449. final_configuration
  1450. # Nettoyage final : supprimer les fichiers de déploiement dans /boot/firmware
  1451. # qui ont fait leur job. On préserve bootstrap_token.json (requis pour le
  1452. # bootstrap initial avec waouw-admin lors de l'onboarding).
  1453. local boot_dir="/boot/firmware"
  1454. [ -d "$boot_dir" ] || boot_dir="/boot"
  1455. for f in waouw-deploy.zip waouw-install.sh waouw-activate.sh waouw-activate.log \
  1456. waouw-activate.ok waouw-deploy-log.sh waouw-deploy-status.txt \
  1457. install-os-prereqs.sh WAOUW-README.txt waouw-install-error.txt \
  1458. waouw-firstboot.service; do
  1459. [ -f "$boot_dir/$f" ] && sudo rm -f "$boot_dir/$f"
  1460. done
  1461. success "Installation WaouW COMPLETE terminée avec succès !"
  1462. }
  1463. main() {
  1464. _deploy_step "install-complete" "running" "Démarrage installation WaouW COMPLETE"
  1465. echo ""
  1466. echo "██╗ ██╗ █████╗ ██████╗ ██╗ ██╗██╗ ██╗"
  1467. echo "██║ ██║██╔══██╗██╔═══██╗██║ ██║██║ ██║"
  1468. echo "██║ █╗ ██║███████║██║ ██║██║ ██║██║ █╗ ██║"
  1469. echo "██║███╗██║██╔══██║██║ ██║██║ ██║██║███╗██║"
  1470. echo "╚███╔███╔╝██║ ██║╚██████╔╝╚██████╔╝╚███╔███╔╝"
  1471. echo " ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══╝╚══╝ "
  1472. echo ""
  1473. echo " v2.0 COMPLETE EDITION"
  1474. echo " Plateforme d'hébergement web complète"
  1475. echo "=============================================="
  1476. echo ""
  1477. _deploy_step "install-complete" "running" "Vérification prérequis"
  1478. check_requirements
  1479. _deploy_step "install-complete" "running" "Installation Docker"
  1480. install_docker
  1481. _deploy_step "install-complete" "running" "Installation WaouW (services, config, déploiement)"
  1482. install_waouw
  1483. _deploy_step "install-complete" "ok" "Installation terminée avec succès"
  1484. echo ""
  1485. echo "🎉 WaouW v2.0 COMPLETE installé avec succès !"
  1486. echo ""
  1487. echo "🌐 ACCÈS WEB :"
  1488. echo " Interface principale : http://waouw.local"
  1489. echo " Webmail (Roundcube) : http://waouw.local/webmail"
  1490. echo " Cloud (Nextcloud) : http://waouw.local/nextcloud"
  1491. echo " Admin Email : http://waouw.local/mailadmin"
  1492. echo " Sécurité (Fail2ban) : http://waouw.local/security"
  1493. echo " VPN (OpenVPN) : http://waouw.local/vpn"
  1494. echo " Logs centralisés : http://waouw.local/logs"
  1495. echo " Métriques (Grafana) : http://waouw.local/dashboard"
  1496. echo ""
  1497. echo "🛠️ OUTILS SYSTÈME :"
  1498. echo " Webmin : https://waouw.local:10000"
  1499. echo " phpMyAdmin : https://waouw.local/phpmyadmin"
  1500. echo ""
  1501. echo "💻 COMMANDES DISPONIBLES :"
  1502. echo " waouw status - Afficher le statut complet"
  1503. echo " waouw logs - Voir les logs en temps réel"
  1504. echo " waouw restart - Redémarrer tous les services"
  1505. echo " waouw stop - Arrêter tous les services"
  1506. echo " waouw start - Démarrer tous les services"
  1507. echo " waouw update - Mettre à jour WaouW"
  1508. echo " waouw backup - Lancer une sauvegarde complète"
  1509. echo " waouw passwords - Afficher les mots de passe"
  1510. echo ""
  1511. echo "📁 CONFIGURATION :"
  1512. echo " Dossier principal : $WAOUW_HOME"
  1513. echo " Logs système : /var/log/waouw"
  1514. echo " Certificats SSL : /etc/waouw/certs"
  1515. echo " Mots de passe : $WAOUW_HOME/PASSWORDS.txt"
  1516. echo ""
  1517. echo "🔧 SERVICES INSTALLÉS :"
  1518. echo " ✅ Interface Web (React + FastAPI + PostgreSQL + Redis)"
  1519. echo " ✅ Proxy inverse (Traefik + SSL automatique)"
  1520. echo " ✅ Stack Email complète (Postfix + Dovecot + Roundcube + Admin)"
  1521. echo " ✅ Cloud personnel (Nextcloud avec Redis)"
  1522. echo " ✅ Sécurité complète (Fail2ban + UFW + OpenVPN)"
  1523. echo " ✅ Monitoring avancé (Graylog + Grafana + Prometheus)"
  1524. echo " ✅ Synchronisation (rsync + lsyncd + rclone)"
  1525. echo " ✅ Administration (Webmin + phpMyAdmin)"
  1526. echo " ✅ Agent device (heartbeat + métriques système)"
  1527. echo " ✅ Sauvegarde automatique (avec rotation)"
  1528. echo ""
  1529. echo "⚡ PREMIÈRE UTILISATION :"
  1530. echo " 1. Ouvrir http://waouw.local dans votre navigateur"
  1531. echo " 2. Suivre l'onboarding affiché par le boîtier"
  1532. echo " 3. Saisir les identifiants client waouw-admin demandés par l'onboarding"
  1533. echo " 4. Laisser le boîtier finaliser l'activation online et la création des accès locaux"
  1534. echo " 5. Récupérer les identifiants remis par le flux d'onboarding"
  1535. echo " 6. Lire le fichier PASSWORDS.txt pour les autres services"
  1536. echo ""
  1537. echo "🔐 SÉCURITÉ :"
  1538. echo " - Firewall UFW activé avec ports nécessaires"
  1539. echo " - Fail2ban configuré pour protection anti-intrusion"
  1540. echo " - SSL automatique avec Let's Encrypt"
  1541. echo " - Services isolés dans des conteneurs Docker"
  1542. echo " - Mots de passe aléatoires générés"
  1543. echo ""
  1544. echo "📖 SUPPORT :"
  1545. echo " - Documentation : $WAOUW_HOME/README.md"
  1546. echo " - Logs : waouw logs"
  1547. echo " - Status : waouw status"
  1548. echo ""
  1549. warn "IMPORTANT: Notez vos mots de passe depuis $WAOUW_HOME/PASSWORDS.txt et supprimez ce fichier !"
  1550. echo ""
  1551. }
  1552. main "$@"