| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831 |
- #!/bin/bash
- set -eo pipefail
- # WaouW v2.0 COMPLETE - Installation Script
- # Compatible: Raspberry Pi OS, Ubuntu ARM64
- # Requirements: Docker, Docker Compose
- # Features: Email, Cloud, VPN, Security, Monitoring
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
- PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
- WAOUW_USER="waouw"
- WAOUW_HOME="/opt/waouw"
- # Garantir que $WAOUW_HOME/DEPLOY et les autres sous-dossiers sont accessibles
- if [ "$SCRIPT_DIR" != "$WAOUW_HOME/DEPLOY" ] && [ ! -e "$WAOUW_HOME/DEPLOY" ]; then
- ln -sfn "$SCRIPT_DIR" "$WAOUW_HOME/DEPLOY"
- fi
- for subdir in BACKEND UI DEVICE_AGENT SYNC_MANAGER BACKUP_MANAGER; do
- if [ -d "$SCRIPT_DIR/../$subdir" ] && [ ! -e "$WAOUW_HOME/$subdir" ]; then
- ln -sfn "$SCRIPT_DIR/../$subdir" "$WAOUW_HOME/$subdir"
- fi
- done
- # Désactiver IPv6 complètement (évite les DNS IPv6 link-local qui cassent les pulls Docker)
- sysctl -w net.ipv6.conf.all.disable_ipv6=1 2>/dev/null || true
- sysctl -w net.ipv6.conf.default.disable_ipv6=1 2>/dev/null || true
- sysctl -w net.ipv6.conf.eth0.disable_ipv6=1 2>/dev/null || true
- sysctl -w net.ipv6.conf.lo.disable_ipv6=1 2>/dev/null || true
- echo "net.ipv6.conf.all.disable_ipv6=1" >> /etc/sysctl.conf 2>/dev/null || true
- echo "net.ipv6.conf.default.disable_ipv6=1" >> /etc/sysctl.conf 2>/dev/null || true
- # DNS fiable: forcer systemd-resolved en IPv4 uniquement
- mkdir -p /etc/systemd/resolved.conf.d
- 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
- systemctl restart systemd-resolved 2>/dev/null || true
- # CRITIQUE — override du watchdog systemd Raspberry Pi OS
- # Le drop-in /usr/lib/systemd/system.conf.d/40-rpi-enable-watchdog.conf force
- # RuntimeWatchdogSec=1m, ce qui est trop court pour un Pi 4 qui doit booter
- # 24 containers Docker en parallele (load avg > 7 au boot). Sans override,
- # le watchdog hardware reset le SoC pendant le boot -> dirty filesystem ext4
- # -> reboot loop. Cause documentee dans memory + DEPLOY/systemd/.
- # Voir aussi : DEPLOY/systemd/99-waouw-watchdog.conf (template authoritative)
- mkdir -p /etc/systemd/system.conf.d
- if [ -f "$SCRIPT_DIR/systemd/99-waouw-watchdog.conf" ]; then
- cp "$SCRIPT_DIR/systemd/99-waouw-watchdog.conf" /etc/systemd/system.conf.d/99-waouw-watchdog.conf
- else
- # Fallback inline si le template n'a pas ete copie
- cat > /etc/systemd/system.conf.d/99-waouw-watchdog.conf << 'WDOG_EOF'
- [Manager]
- RuntimeWatchdogSec=10min
- RebootWatchdogSec=5min
- WDOG_EOF
- fi
- systemctl daemon-reexec 2>/dev/null || true
- # Forcer Docker à utiliser le DNS IPv4 (indépendant du système)
- mkdir -p /etc/docker
- echo '{"dns": ["8.8.8.8", "8.8.4.4"]}' > /etc/docker/daemon.json
- mkdir -p /var/log/waouw-deploy
- [ -f "$SCRIPT_DIR/waouw-deploy-log.sh" ] && _WAOUW_SCRIPT="install-complete" . "$SCRIPT_DIR/waouw-deploy-log.sh"
- _deploy_log() { waouw_deploy_log "INFO" "$@" 2>/dev/null || log "$@"; }
- _deploy_step() { waouw_deploy_step "$@" 2>/dev/null || true; }
- _deploy_err() { waouw_deploy_error "$@" 2>/dev/null || error "$@"; }
- # Colors for output
- RED='\033[0;31m'
- GREEN='\033[0;32m'
- YELLOW='\033[1;33m'
- BLUE='\033[0;34m'
- NC='\033[0m' # No Color
- log() {
- echo -e "${GREEN}[INFO]${NC} $1"
- }
- warn() {
- echo -e "${YELLOW}[WARN]${NC} $1"
- }
- error() {
- echo -e "${RED}[ERROR]${NC} $1"
- }
- success() {
- echo -e "${BLUE}[SUCCESS]${NC} $1"
- }
- fix_clock() {
- timedatectl set-ntp true 2>/dev/null || true
- systemctl restart systemd-timesyncd 2>/dev/null || true
- local http_date=""
- if command -v python3 >/dev/null 2>&1; then
- http_date="$(python3 - <<'PY'
- import urllib.request
- for url in ("http://admin.waouw.eu", "http://deb.debian.org"):
- try:
- with urllib.request.urlopen(url, timeout=10) as response:
- print(response.headers.get("Date", ""))
- break
- except Exception:
- pass
- PY
- )"
- fi
- http_date="$(printf '%s\n' "$http_date" | sed '/^$/d' | head -n1)"
- if [[ -n "$http_date" ]]; then
- local remote_ts=""
- local now_ts=""
- remote_ts="$(date -u -d "$http_date" '+%s' 2>/dev/null || true)"
- now_ts="$(date -u '+%s' 2>/dev/null || echo 0)"
- if [[ -n "$remote_ts" && "$remote_ts" -gt 1700000000 ]] && { [[ "$now_ts" -lt $((remote_ts - 300)) ]] || [[ "$now_ts" -gt $((remote_ts + 86400)) ]]; }; then
- date -u -s "@$remote_ts" >/dev/null 2>&1 || true
- hwclock --systohc >/dev/null 2>&1 || true
- _deploy_log "Horloge système recalée depuis la date HTTP: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
- fi
- fi
- }
- check_requirements() {
- log "Vérification des prérequis..."
-
- # Check OS (non-interactif: on continue avec avertissement)
- if ! grep -Eq "Raspberry Pi OS|Raspbian|Debian|Ubuntu" /etc/os-release 2>/dev/null; then
- warn "OS non officiellement supporté détecté; poursuite automatique (mode non-interactif)."
- fi
-
- # Check architecture
- ARCH=$(uname -m)
- if [[ "$ARCH" != "aarch64" && "$ARCH" != "armv7l" && "$ARCH" != "x86_64" ]]; then
- error "Architecture non supportée: $ARCH"
- exit 1
- fi
-
- # Privileges: allow root to keep flow non-interactive
- if [[ $EUID -ne 0 ]]; then
- warn "Execution non-root detectee, sudo sera requis pour certaines etapes."
- fi
-
- # Check available memory (minimum 2GB recommended)
- MEMORY_GB=$(free -g | awk '/^Mem:/ {print $2}')
- if [[ $MEMORY_GB -lt 2 ]]; then
- warn "Mémoire faible détectée (${MEMORY_GB}GB). 2GB+ recommandés pour tous les services."
- fi
-
- # Check disk space (minimum 8GB free)
- DISK_FREE_GB=$(df / | awk 'NR==2 {print int($4/1024/1024)}')
- if [[ $DISK_FREE_GB -lt 8 ]]; then
- error "Espace disque insuffisant. 8GB+ requis, ${DISK_FREE_GB}GB disponible."
- exit 1
- fi
-
- success "Prérequis validés"
- }
- install_docker() {
- if command -v docker &> /dev/null && docker compose version &> /dev/null; then
- log "Docker déjà installé"
- return
- fi
-
- log "Installation de Docker..."
-
- curl -fsSL https://get.docker.com | sh
-
- sudo usermod -aG docker $USER
-
- sudo systemctl enable docker
- sudo systemctl start docker
-
- success "Docker installé"
- }
- # Install additional system dependencies
- install_system_dependencies() {
- log "Installation des dépendances système..."
- fix_clock
-
- # Update package lists
- sudo apt-get update
-
- # Préconfigurer Postfix pour éviter tout dialogue interactif
- sudo debconf-set-selections <<< "postfix postfix/mailname string $(hostname -f)"
- sudo debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
- export DEBIAN_FRONTEND=noninteractive
- # Install additional packages for email, VPN, security
- sudo DEBIAN_FRONTEND=noninteractive apt-get install -y \
- ufw \
- fail2ban \
- postfix \
- dovecot-core \
- avahi-daemon \
- avahi-utils \
- libnss-mdns \
- openvpn \
- easy-rsa \
- certbot \
- apache2-utils \
- jq \
- curl \
- wget \
- rsync \
- lsyncd \
- rclone \
- tree \
- htop \
- iotop \
- net-tools \
- dnsutils \
- openssl \
- wireguard-tools \
- mailutils
- # Enable mDNS so the box is reachable via waouw.local
- # Restrict Avahi to eth0/wlan0 only - Docker veth interfaces would break mDNS when containers restart
- if ! grep -q '^allow-interfaces=' /etc/avahi/avahi-daemon.conf 2>/dev/null; then
- sudo sed -i '/^\[server\]/a allow-interfaces=eth0,wlan0' /etc/avahi/avahi-daemon.conf
- fi
- sudo systemctl enable avahi-daemon
- sudo systemctl restart avahi-daemon || sudo systemctl start avahi-daemon
- # Fix WiFi Raspberry Pi OS Bookworm : brcmfmac-wcc doit être chargé AVANT brcmfmac
- # sinon le module principal échoue à binder et le WiFi n'est pas détecté.
- sudo tee /etc/modprobe.d/wifi-wcc.conf > /dev/null <<'WIFI_EOF'
- # WaouW : fix WiFi Bookworm — softdep force l'ordre de chargement
- softdep brcmfmac pre: brcmfmac-wcc
- WIFI_EOF
- sudo update-initramfs -u 2>/dev/null || true
- success "Dépendances système installées"
- }
- create_waouw_user() {
- if id "$WAOUW_USER" &>/dev/null; then
- log "Utilisateur $WAOUW_USER existe déjà"
- else
- log "Création de l'utilisateur $WAOUW_USER..."
- sudo useradd -r -s /bin/bash -d "$WAOUW_HOME" -m "$WAOUW_USER"
- fi
- # Important: au premier boot, le groupe docker n'existe pas encore.
- # Si l'utilisateur a été créé avant l'installation de Docker, il faut
- # rejouer explicitement ces rattachements.
- sudo usermod -aG docker "$WAOUW_USER" 2>/dev/null || true
- sudo usermod -aG mail "$WAOUW_USER" 2>/dev/null || true
- sudo usermod -aG ssl-cert "$WAOUW_USER" 2>/dev/null || true
- success "Utilisateur $WAOUW_USER prêt"
- }
- create_directories() {
- log "Création des répertoires..."
-
- # Main directories
- sudo mkdir -p "$WAOUW_HOME"/{config,data,logs,backups,scripts,certs}
-
- # Service-specific directories
- sudo mkdir -p "$WAOUW_HOME"/data/{postgres,redis,traefik}
- sudo mkdir -p "$WAOUW_HOME"/data/{nextcloud,roundcube,postfix,dovecot}
- sudo mkdir -p "$WAOUW_HOME"/data/{grafana,prometheus,graylog,elasticsearch}
- sudo mkdir -p "$WAOUW_HOME"/data/{fail2ban,openvpn}
-
- # Log directories
- sudo mkdir -p /var/log/waouw
-
- # Mail directories
- sudo mkdir -p /var/mail/vhosts
- sudo mkdir -p /etc/postfix/sql
- sudo mkdir -p /etc/dovecot/sql
-
- # Certificates directory
- sudo mkdir -p /etc/waouw/certs
-
- # Set ownership
- sudo chown -R "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME"
- sudo chown -R "$WAOUW_USER:$WAOUW_USER" /var/log/waouw
- sudo chown -R mail:mail /var/mail/vhosts
- sudo chown -R 999:999 /etc/waouw
-
- # Set permissions
- sudo chmod -R 755 "$WAOUW_HOME"
- sudo chmod 755 /etc/waouw
- sudo mkdir -p /etc/waouw/keys /etc/waouw/certs
- sudo chmod 755 /etc/waouw/keys
- sudo chmod -R 770 /var/mail/vhosts
- sudo chmod -R 750 /etc/waouw/certs
- # Pre-create avahi files so the backend container (user waouw) can write to them
- sudo touch /etc/waouw/avahi-site-hosts /etc/waouw/avahi-reload-signal
- sudo chown "$WAOUW_USER:$WAOUW_USER" /etc/waouw/avahi-site-hosts /etc/waouw/avahi-reload-signal
- # Backend container runs as uid 999, host user is typically uid 1000.
- # Keep these files world-writable to avoid mDNS registration failures.
- sudo chmod 666 /etc/waouw/avahi-site-hosts /etc/waouw/avahi-reload-signal
- # Sites data directory for FTP access (bind-mounted in CMS containers)
- sudo mkdir -p /opt/waouw/sites-data
- sudo chmod 777 /opt/waouw/sites-data
- # FTP pending directory (backend writes requests, host script processes)
- sudo mkdir -p /etc/waouw/ftp-pending
- sudo chmod 777 /etc/waouw/ftp-pending
-
- success "Répertoires créés"
- }
- ensure_device_runtime_files() {
- log "Préparation des fichiers runtime /etc/waouw..."
- local device_id=""
- if sudo test -s /etc/waouw/device_id; then
- device_id=$(sudo tr -d '\r\n' < /etc/waouw/device_id || true)
- fi
- if [[ -z "$device_id" ]] && [[ -r /proc/cpuinfo ]]; then
- device_id=$(awk '/^Serial/ {print $3}' /proc/cpuinfo | tail -1)
- fi
- if [[ -z "$device_id" ]] && [[ -r /etc/machine-id ]]; then
- device_id=$(tr -d '\r\n' < /etc/machine-id | cut -c1-16)
- fi
- if [[ -n "$device_id" ]]; then
- echo -n "$device_id" | sudo tee /etc/waouw/device_id >/dev/null
- sudo chmod 644 /etc/waouw/device_id
- sudo chown 999:999 /etc/waouw/device_id
- fi
- sudo touch /etc/waouw/claim_code /etc/waouw/desired_hostname /etc/waouw/onboarding-state.json
- sudo chown 999:999 /etc/waouw/claim_code /etc/waouw/desired_hostname /etc/waouw/onboarding-state.json
- sudo chmod 644 /etc/waouw/claim_code /etc/waouw/desired_hostname /etc/waouw/onboarding-state.json
- sudo mkdir -p /etc/waouw/keys
- sudo chown 999:999 /etc/waouw/keys
- sudo chmod 755 /etc/waouw/keys
- sudo sh -c 'for f in /etc/waouw/keys/*; do [ -f "$f" ] && chown 999:999 "$f" && chmod 644 "$f"; done' || true
- success "Fichiers runtime /etc/waouw prêts"
- }
- install_activation_bootstrap() {
- log "Configuration activation (bootstrap)..."
- # Copier le token bootstrap depuis /boot vers /etc/waouw
- local BOOT_TOKEN=""
- if [[ -f "/boot/waouw-bootstrap-token.txt" ]]; then
- BOOT_TOKEN=$(tr -d '\r\n' < "/boot/waouw-bootstrap-token.txt" || true)
- elif [[ -f "/boot/firmware/waouw-bootstrap-token.txt" ]]; then
- BOOT_TOKEN=$(tr -d '\r\n' < "/boot/firmware/waouw-bootstrap-token.txt" || true)
- fi
- if [[ -n "$BOOT_TOKEN" ]]; then
- sudo mkdir -p /etc/waouw/keys
- echo -n "$BOOT_TOKEN" | sudo tee /etc/waouw/bootstrap_token >/dev/null
- # 644: lisible par le container backend (UID 999) et l'hôte (UID 1000)
- # Le token bootstrap n'est pas un secret à long terme (usage unique par device)
- sudo chmod 644 /etc/waouw/bootstrap_token
- sudo chown "$WAOUW_USER:$WAOUW_USER" /etc/waouw/bootstrap_token
- success "Token bootstrap installé (/etc/waouw/bootstrap_token)"
- else
- warn "Token bootstrap absent sur /boot. L'activation online ne fonctionnera pas."
- fi
- # Lire l'URL du waouw-admin online. Par défaut, on pointe sur la prod.
- local ADMIN_URL="https://admin.waouw.eu"
- if [[ -f "/boot/waouw-admin-url.txt" ]]; then
- ADMIN_URL=$(tr -d '\r\n' < "/boot/waouw-admin-url.txt" || true)
- elif [[ -f "/boot/firmware/waouw-admin-url.txt" ]]; then
- ADMIN_URL=$(tr -d '\r\n' < "/boot/firmware/waouw-admin-url.txt" || true)
- fi
- if [[ -n "$ADMIN_URL" ]]; then
- export WAOUW_ADMIN_URL="$ADMIN_URL"
- success "WAOUW_ADMIN_URL détectée: $WAOUW_ADMIN_URL"
- fi
- }
- copy_waouw_files() {
- log "Vérification des fichiers WaouW..."
- # Files are already in place from the archive extraction
- # Just ensure correct ownership
- sudo chown -R "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME"
- success "Fichiers vérifiés"
- }
- install_update_cli() {
- log "Installation de l'outil de mise à jour..."
- sudo mkdir -p /usr/local/bin
- sudo mkdir -p /var/log/waouw/updates
- # Copy hardened update scripts from repo
- sudo cp -f "$WAOUW_HOME/DEPLOY/scripts/waouw-update" /usr/local/bin/waouw-update
- sudo cp -f "$WAOUW_HOME/DEPLOY/scripts/waouw-auto-update.sh" /usr/local/bin/waouw-auto-update.sh
- sudo chmod +x /usr/local/bin/waouw-update /usr/local/bin/waouw-auto-update.sh
- # Systemd path unit: watches for pending-update.json trigger file
- sudo tee /etc/systemd/system/waouw-update.path > /dev/null <<'EOF'
- [Unit]
- Description=Watch for WaouW update trigger
- [Path]
- PathChanged=/var/lib/docker/volumes/waouw_backup_data/_data/updates/pending-update.json
- PathModified=/var/lib/docker/volumes/waouw_backup_data/_data/updates/pending-update.json
- [Install]
- WantedBy=multi-user.target
- EOF
- sudo tee /etc/systemd/system/waouw-update.service > /dev/null <<'EOF'
- [Unit]
- Description=Apply WaouW update
- [Service]
- Type=oneshot
- ExecStart=/usr/local/bin/waouw-auto-update.sh
- TimeoutStartSec=1200
- EOF
- sudo systemctl daemon-reload
- sudo systemctl enable waouw-update.path
- sudo systemctl start waouw-update.path
- success "Outil de mise à jour installé (scripts + systemd trigger)"
- }
- generate_config() {
- log "Génération de la configuration..."
- # Reprise d'installation: si un .env existe déjà, on réutilise ses secrets
- # pour éviter de désynchroniser Postgres et les autres services stateful.
- if [[ -f "$WAOUW_HOME/.env" ]]; then
- set -a
- # shellcheck disable=SC1090
- . "$WAOUW_HOME/.env" || true
- set +a
- log "Réutilisation des secrets existants depuis $WAOUW_HOME/.env"
- fi
- # Generate random passwords (openssl rand, pas de dépendance à pwgen)
- _rndpw() { openssl rand -base64 $(( $1 * 2 )) 2>/dev/null | tr -d '/+=\n' | head -c "$1"; }
- DB_PASSWORD=${POSTGRES_PASSWORD:-$(_rndpw 32)}
- JWT_SECRET=${JWT_SECRET_KEY:-$(openssl rand -hex 32)}
- DEVICE_SECRET=${DEVICE_HMAC_SECRET:-$(openssl rand -hex 32)}
- MAIL_DB_PASSWORD=${MAIL_MYSQL_PASSWORD:-$(_rndpw 32)}
- NEXTCLOUD_ADMIN_PASSWORD=${NEXTCLOUD_ADMIN_PASSWORD:-$(_rndpw 16)}
- GRAFANA_ADMIN_PASSWORD=${GRAFANA_ADMIN_PASSWORD:-$(_rndpw 16)}
- GRAYLOG_PASSWORD_SECRET=${GRAYLOG_PASSWORD_SECRET:-$(_rndpw 96)}
- GRAYLOG_ROOT_PASSWORD_SHA2=$(echo -n "admin" | sha256sum | cut -d" " -f1)
- MAIL_MYSQL_ROOT_PASSWORD=${MAIL_MYSQL_ROOT_PASSWORD:-$(_rndpw 32)}
- MAIL_MYSQL_PASSWORD2=${MAIL_MYSQL_PASSWORD:-$(_rndpw 32)}
- NEXTCLOUD_MYSQL_ROOT_PASSWORD=${NEXTCLOUD_MYSQL_ROOT_PASSWORD:-$(_rndpw 32)}
- NEXTCLOUD_MYSQL_PASSWORD2=${NEXTCLOUD_MYSQL_PASSWORD:-$(_rndpw 32)}
- PHPMYADMIN_PASSWORD=${PHPMYADMIN_PASSWORD:-$(_rndpw 16)}
- WEBMIN_ROOT_PASSWORD=${WEBMIN_ROOT_PASSWORD:-$(_rndpw 16)}
- SMTP_PASSWORD=${SMTP_PASSWORD:-$(_rndpw 32)}
-
- # IP LAN et passerelle du boitier (pour onboarding/diagnostics)
- 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 "")
- WAOUW_GATEWAY_IP=$(ip route 2>/dev/null | awk '/default/ {print $3; exit}' || echo "")
-
- # Create .env file
- sudo tee "$WAOUW_HOME/.env" > /dev/null <<EOF
- # WaouW v2.0 COMPLETE Environment Configuration
- # Generated on $(date)
- # =============================================================================
- # DOMAIN & TLS
- # =============================================================================
- WAOUW_DOMAIN=waouw.local
- ACME_EMAIL=ssl-agent@waouw.tech
- # =============================================================================
- # RESEAU (IP LAN boitier, passerelle - pour onboarding)
- # =============================================================================
- WAOUW_LAN_IP=$WAOUW_LAN_IP
- WAOUW_GATEWAY_IP=$WAOUW_GATEWAY_IP
- # =============================================================================
- # CORE DATABASE
- # =============================================================================
- POSTGRES_PASSWORD=$DB_PASSWORD
- DATABASE_URL=postgresql://waouw:$DB_PASSWORD@postgres:5432/waouw
- # =============================================================================
- # CACHE
- # =============================================================================
- REDIS_URL=redis://redis:6379/0
- # =============================================================================
- # SECURITY
- # =============================================================================
- JWT_SECRET_KEY=$JWT_SECRET
- DEVICE_HMAC_SECRET=$DEVICE_SECRET
- # =============================================================================
- # LICENCE / ACTIVATION (waouw-admin online)
- # =============================================================================
- WAOUW_ADMIN_URL=${WAOUW_ADMIN_URL:-https://admin.waouw.eu}
- # =============================================================================
- # EMAIL SERVICES
- # =============================================================================
- MAIL_MYSQL_ROOT_PASSWORD=$MAIL_MYSQL_ROOT_PASSWORD
- MAIL_MYSQL_PASSWORD=$MAIL_DB_PASSWORD
- SMTP_HOST=postfix
- SMTP_PORT=587
- SMTP_USERNAME=waouw@waouw.local
- SMTP_PASSWORD=$SMTP_PASSWORD
- # =============================================================================
- # NEXTCLOUD CLOUD
- # =============================================================================
- NEXTCLOUD_MYSQL_ROOT_PASSWORD=$NEXTCLOUD_MYSQL_ROOT_PASSWORD
- NEXTCLOUD_MYSQL_PASSWORD=$NEXTCLOUD_MYSQL_PASSWORD2
- NEXTCLOUD_ADMIN_PASSWORD=$NEXTCLOUD_ADMIN_PASSWORD
- # =============================================================================
- # SYSTEM MANAGEMENT
- # =============================================================================
- PHPMYADMIN_PASSWORD=$PHPMYADMIN_PASSWORD
- WEBMIN_ROOT_PASSWORD=$WEBMIN_ROOT_PASSWORD
- # =============================================================================
- # SECURITY & VPN
- # =============================================================================
- F2B_MAXRETRY=5
- F2B_BANTIME=3600
- F2B_FINDTIME=600
- VPN_NETWORK=10.8.0.0/24
- VPN_CLIENT_NETWORK=192.168.1.0/24
- # =============================================================================
- # BACKUP & SYNC
- # =============================================================================
- BACKUP_RETENTION_DAYS=7
- BACKUP_SCHEDULE="0 2 * * *"
- # =============================================================================
- # MONITORING & LOGS
- # =============================================================================
- GRAYLOG_PASSWORD_SECRET=$GRAYLOG_PASSWORD_SECRET
- GRAYLOG_ROOT_PASSWORD_SHA2=$GRAYLOG_ROOT_PASSWORD_SHA2
- GRAFANA_ADMIN_PASSWORD=$GRAFANA_ADMIN_PASSWORD
- PROMETHEUS_ENABLED=true
- GRAFANA_ENABLED=true
- OPENSEARCH_ENABLED=true
- MONGO_ENABLED=true
- LOG_LEVEL=INFO
- METRICS_ENABLED=true
- METRICS_INTERVAL=30
- # =============================================================================
- # RESOURCE LIMITS (Raspberry Pi Optimized)
- # =============================================================================
- POSTGRES_MEMORY_LIMIT=256
- REDIS_MEMORY_LIMIT=128
- BACKEND_MEMORY_LIMIT=512
- NEXTCLOUD_MEMORY_LIMIT=512
- # =============================================================================
- # BUILD
- # =============================================================================
- BUILDPLATFORM=linux/arm64
- # =============================================================================
- # EXTERNAL INTEGRATIONS
- # =============================================================================
- CENTRAL_AUTH_URL=https://your-central-server.com/api
- DEVICE_HEARTBEAT_INTERVAL=30
- # =============================================================================
- # TIMEZONE
- # =============================================================================
- TZ=Europe/Paris
- # =============================================================================
- # DOCKER HOST INTEGRATION
- # GID du groupe "docker" sur l'hôte — permet au container backend d'accéder
- # au socket Docker (/var/run/docker.sock) pour déployer les sites.
- # =============================================================================
- DOCKER_GID=$(getent group docker | cut -d: -f3 || echo "985")
- EOF
-
- # Set secure permissions
- sudo chmod 600 "$WAOUW_HOME/.env"
- sudo chown "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME/.env"
-
- # Save passwords for admin
- sudo tee "$WAOUW_HOME/PASSWORDS.txt" > /dev/null <<EOF
- WaouW v2.0 COMPLETE - Mots de passe générés
- ==========================================
- Interface Web:
- URL: http://waouw.local
- Accès admin local: généré par le flux d'onboarding
- Activation online: déclenchée pendant l'onboarding depuis le boîtier
- Nextcloud:
- URL: http://waouw.local/nextcloud
- Admin: admin
- Password: $NEXTCLOUD_ADMIN_PASSWORD
- Grafana:
- URL: http://waouw.local/dashboard
- Admin: admin
- Password: $GRAFANA_ADMIN_PASSWORD
- Webmail (Roundcube):
- URL: http://waouw.local/webmail
- Utilise les comptes email créés
- phpMyAdmin:
- URL: http://waouw.local/phpmyadmin
- User: root
- Password: $DB_PASSWORD
- Base de données PostgreSQL:
- Host: localhost:5432
- Database: waouw
- User: waouw
- Password: $DB_PASSWORD
- IMPORTANT: Gardez ce fichier en sécurité et supprimez-le après avoir noté les mots de passe !
- EOF
-
- sudo chown "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME/PASSWORDS.txt"
- sudo chmod 600 "$WAOUW_HOME/PASSWORDS.txt"
-
- success "Configuration générée"
- }
- setup_security() {
- log "Configuration de la sécurité..."
-
- # Configure UFW firewall
- sudo ufw --force reset
- sudo ufw default deny incoming
- sudo ufw default allow outgoing
- sudo ufw allow ssh
- sudo ufw allow 80/tcp
- sudo ufw allow 443/tcp
- sudo ufw allow 7165/tcp
- sudo ufw allow 25/tcp # SMTP
- sudo ufw allow 587/tcp # SMTP Submission
- sudo ufw allow 993/tcp # IMAPS
- sudo ufw allow 995/tcp # POP3S
- sudo ufw allow 1194/udp # OpenVPN
- sudo ufw allow 10000/tcp # Webmin
- sudo ufw allow 5353/udp # mDNS (waouw.local)
- sudo ufw --force enable
-
- # Configure basic fail2ban
- sudo systemctl enable fail2ban
- sudo systemctl start fail2ban
-
- success "Sécurité configurée"
- }
- setup_ssl_certificates() {
- log "Configuration des certificats SSL..."
-
- # Generate self-signed certificate for initial setup
- if [[ ! -f /etc/waouw/certs/waouw.local.crt ]]; then
- sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
- -keyout /etc/waouw/certs/waouw.local.key \
- -out /etc/waouw/certs/waouw.local.crt \
- -subj "/C=FR/ST=France/L=Local/O=WaouW/CN=waouw.local"
- fi
-
- # Set permissions
- sudo chown -R "$WAOUW_USER:$WAOUW_USER" /etc/waouw/certs
- sudo chmod 600 /etc/waouw/certs/*.key
- sudo chmod 644 /etc/waouw/certs/*.crt
-
- success "Certificats SSL configurés"
- }
- setup_traefik_config() {
- log "Configuration de Traefik..."
- # Dossier de configuration Traefik
- if [[ ! -d /etc/waouw/traefik ]]; then
- sudo mkdir -p /etc/waouw/traefik
- fi
- # Copier les fichiers Traefik depuis le dossier du script d'installation
- if [[ -f "$SCRIPT_DIR/traefik/traefik.yml" ]]; then
- sudo cp "$SCRIPT_DIR/traefik/traefik.yml" /etc/waouw/traefik/traefik.yml
- else
- warn "Fichier traefik/traefik.yml introuvable"
- fi
- if [[ -f "$SCRIPT_DIR/traefik/dynamic.yml" ]]; then
- sudo cp "$SCRIPT_DIR/traefik/dynamic.yml" /etc/waouw/traefik/dynamic.yml
- else
- warn "Fichier traefik/dynamic.yml introuvable"
- fi
- # Dossier des certificats ACME
- sudo mkdir -p /etc/waouw/traefik/certificates
- if [[ ! -f /etc/waouw/traefik/certificates/acme.json ]]; then
- echo '{}' | sudo tee /etc/waouw/traefik/certificates/acme.json >/dev/null
- sudo chmod 600 /etc/waouw/traefik/certificates/acme.json
- fi
- success "Traefik configuré"
- }
- setup_docker_env() {
- log "Configuration de l'environnement Docker..."
-
- # Create Docker networks
- docker network create traefik 2>/dev/null || true
-
- # Pull base images for better startup time
- docker pull traefik:v2.11
- docker pull postgres:15-alpine
- docker pull redis:7-alpine
- docker pull nextcloud:28-apache
- docker pull roundcube/roundcubemail:latest-apache
-
- success "Environnement Docker configuré"
- }
- initialize_openvpn() {
- log "Pré-initialisation OpenVPN (PKI/config)..."
- local VPN_IMAGE="lunderhage/openvpn-rpi:latest"
- local DOMAIN="${WAOUW_DOMAIN:-waouw.local}"
- docker volume create waouw_openvpn_data >/dev/null 2>&1 || true
- docker volume create waouw_openvpn_config >/dev/null 2>&1 || true
- # If already initialized, skip.
- if docker run --rm -v waouw_openvpn_data:/etc/openvpn "$VPN_IMAGE" sh -lc "test -f /etc/openvpn/ovpn_env.sh"; then
- log "OpenVPN déjà initialisé"
- return
- fi
- if ! docker run --rm -v waouw_openvpn_data:/etc/openvpn "$VPN_IMAGE" ovpn_genconfig -u "udp://${DOMAIN}:1194"; then
- warn "ovpn_genconfig a échoué, le toggle VPN pourra retenter l'initialisation"
- return
- fi
- if ! docker run --rm -v waouw_openvpn_data:/etc/openvpn "$VPN_IMAGE" sh -lc "EASYRSA_BATCH=1 ovpn_initpki nopass"; then
- warn "ovpn_initpki a échoué, le toggle VPN pourra retenter l'initialisation"
- return
- fi
- success "OpenVPN initialisé"
- }
- install_systemd_services() {
- log "Installation des services systemd..."
-
- # Script de detection reseau (IP LAN, passerelle) - execute a chaque demarrage
- sudo tee "$WAOUW_HOME/scripts/waouw-network-detect.sh" > /dev/null <<'SCRIPT'
- #!/bin/bash
- ENV_FILE="/opt/waouw/.env"
- [ ! -f "$ENV_FILE" ] && exit 0
- sed -i '/^WAOUW_LAN_IP=/d' "$ENV_FILE"
- sed -i '/^WAOUW_GATEWAY_IP=/d' "$ENV_FILE"
- LAN=$(hostname -I 2>/dev/null | awk '{print $1}')
- GW=$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')
- [ -n "$LAN" ] && echo "WAOUW_LAN_IP=$LAN" >> "$ENV_FILE"
- [ -n "$GW" ] && echo "WAOUW_GATEWAY_IP=$GW" >> "$ENV_FILE"
- SCRIPT
- sudo chmod +x "$WAOUW_HOME/scripts/waouw-network-detect.sh"
- sudo chown "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME/scripts/waouw-network-detect.sh"
-
- # Create WaouW stack service
- sudo tee /etc/systemd/system/waouw-stack.service > /dev/null <<EOF
- [Unit]
- Description=WaouW v2.0 Complete Stack
- Requires=docker.service
- After=docker.service network-online.target
- [Service]
- Type=oneshot
- RemainAfterExit=yes
- User=$WAOUW_USER
- Group=$WAOUW_USER
- WorkingDirectory=$WAOUW_HOME/DEPLOY
- ExecStartPre=$WAOUW_HOME/scripts/waouw-network-detect.sh
- ExecStart=docker compose --profile vpn up -d
- ExecStartPost=/bin/sh -c 'sleep 5 && /usr/bin/docker start waouw_frontend 2>/dev/null || true'
- ExecStop=docker compose down
- TimeoutStartSec=600
- [Install]
- WantedBy=multi-user.target
- EOF
-
- # Create device agent service
- sudo tee /etc/systemd/system/waouw-agent.service > /dev/null <<EOF
- [Unit]
- Description=WaouW Device Agent
- After=network.target
- [Service]
- Type=simple
- User=$WAOUW_USER
- Group=$WAOUW_USER
- WorkingDirectory=$WAOUW_HOME/DEVICE_AGENT
- ExecStart=/usr/bin/python3 waouw_agent.py
- Restart=always
- RestartSec=10
- [Install]
- WantedBy=multi-user.target
- EOF
-
- # Service waouw-hostname: applique le hostname désiré (écrit par le backend dans /etc/waouw/desired_hostname)
- # et redémarre avahi-daemon pour que <hostname>.local soit accessible via mDNS.
- sudo tee /usr/local/bin/waouw-apply-hostname > /dev/null <<'SCRIPT'
- #!/bin/bash
- DESIRED_FILE="/etc/waouw/desired_hostname"
- [ -f "$DESIRED_FILE" ] || exit 0
- HOSTNAME=$(tr -d '[:space:]' < "$DESIRED_FILE")
- [ -z "$HOSTNAME" ] && exit 0
- CURRENT=$(hostname)
- [ "$HOSTNAME" = "$CURRENT" ] && exit 0
- echo "waouw-hostname: application du hostname '$HOSTNAME' (ancien: '$CURRENT')"
- hostnamectl set-hostname "$HOSTNAME"
- # Mettre à jour /etc/hostname
- echo "$HOSTNAME" > /etc/hostname
- # Mettre à jour /etc/hosts (remplacer l'ancienne entrée 127.0.1.1)
- if grep -q "127.0.1.1" /etc/hosts; then
- sed -i "s/127\.0\.1\.1\s.*/127.0.1.1\t$HOSTNAME/" /etc/hosts
- else
- echo "127.0.1.1 $HOSTNAME" >> /etc/hosts
- fi
- # Redémarrer Avahi pour diffuser le nouveau nom mDNS
- systemctl restart avahi-daemon || true
- echo "waouw-hostname: hostname '$HOSTNAME' appliqué, avahi redémarré."
- SCRIPT
- sudo chmod +x /usr/local/bin/waouw-apply-hostname
- # Systemd path unit: déclenche waouw-hostname.service dès que /etc/waouw/desired_hostname est créé/modifié
- sudo tee /etc/systemd/system/waouw-hostname.path > /dev/null <<'EOF'
- [Unit]
- Description=Surveillance du fichier desired_hostname WaouW
- After=network.target
- [Path]
- PathCreated=/etc/waouw/desired_hostname
- PathModified=/etc/waouw/desired_hostname
- Unit=waouw-hostname.service
- [Install]
- WantedBy=multi-user.target
- EOF
- sudo tee /etc/systemd/system/waouw-hostname.service > /dev/null <<'EOF'
- [Unit]
- Description=Appliquer le hostname WaouW depuis /etc/waouw/desired_hostname
- After=network.target
- [Service]
- Type=oneshot
- ExecStart=/usr/local/bin/waouw-apply-hostname
- EOF
- # Service waouw-relay-tunnel: détecte relay_request.json et configure le tunnel WireGuard
- sudo cp /opt/waouw/DEPLOY/scripts/waouw-relay-tunnel.sh /opt/waouw/scripts/waouw-relay-tunnel.sh 2>/dev/null || true
- sudo chmod +x /opt/waouw/scripts/waouw-relay-tunnel.sh 2>/dev/null || true
- sudo tee /etc/systemd/system/waouw-relay-tunnel.path > /dev/null <<'EOF'
- [Unit]
- Description=Watch for relay tunnel request
- [Path]
- PathExists=/etc/waouw/relay_request.json
- MakeDirectory=yes
- [Install]
- WantedBy=multi-user.target
- EOF
- sudo tee /etc/systemd/system/waouw-relay-tunnel.service > /dev/null <<'EOF'
- [Unit]
- Description=WaouW Relay Tunnel Setup
- After=network-online.target docker.service
- Wants=network-online.target
- [Service]
- Type=oneshot
- ExecStart=/opt/waouw/scripts/waouw-relay-tunnel.sh
- RemainAfterExit=false
- StandardOutput=journal
- StandardError=journal
- [Install]
- WantedBy=multi-user.target
- EOF
- sudo systemctl daemon-reload
- sudo systemctl enable waouw-relay-tunnel.path
- sudo systemctl start waouw-relay-tunnel.path
- # Service waouw-avahi: publie les alias .local des sites via avahi-publish.
- # IMPORTANT: /etc/avahi/hosts ne fonctionne pas pour des alias pointant vers la machine locale
- # (cela provoque des "Local name collision"). On utilise donc avahi-publish -a -R par alias.
- sudo tee /usr/local/bin/waouw-publish-alias > /dev/null <<'SCRIPT'
- #!/bin/bash
- set -euo pipefail
- ALIAS="${1:-}"
- [ -z "$ALIAS" ] && exit 1
- LAN_IP="$(grep '^WAOUW_LAN_IP=' /opt/waouw/.env 2>/dev/null | cut -d= -f2)"
- if [ -z "$LAN_IP" ]; then
- LAN_IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
- fi
- [ -z "$LAN_IP" ] && exit 1
- exec /usr/bin/avahi-publish -a -R "$ALIAS" "$LAN_IP"
- SCRIPT
- sudo chmod +x /usr/local/bin/waouw-publish-alias
- sudo tee /usr/local/bin/waouw-sync-avahi-aliases > /dev/null <<'SCRIPT'
- #!/bin/bash
- set -euo pipefail
- HOSTS_SRC="/etc/waouw/avahi-site-hosts"
- mapfile -t current_units < <(systemctl list-units --full --all 'waouw-avahi-alias@*.service' --no-legend | awk '{print $1}')
- declare -A wanted
- if [ -f "$HOSTS_SRC" ]; then
- while read -r a b _; do
- [ -z "${a:-}" ] && continue
- case "$a" in \#*) continue ;; esac
- # Support both formats:
- # 1) "192.168.1.115 monsite.local"
- # 2) "monsite.local"
- if echo "$a" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'; then
- alias="${b:-}"
- else
- alias="$a"
- fi
- alias="$(echo "$alias" | tr '[:upper:]' '[:lower:]' | xargs)"
- [ -z "$alias" ] && continue
- case "$alias" in
- *.local) wanted["$alias"]=1 ;;
- *) ;;
- esac
- done < "$HOSTS_SRC"
- fi
- # Stop aliases that are no longer present
- for unit in "${current_units[@]}"; do
- [ -z "$unit" ] && continue
- inst="${unit#waouw-avahi-alias@}"
- inst="${inst%.service}"
- alias="$(systemd-escape --unescape "$inst")"
- if [ -z "${wanted[$alias]:-}" ]; then
- systemctl stop "$unit" 2>/dev/null || true
- systemctl disable "$unit" 2>/dev/null || true
- fi
- done
- # Start/update aliases present in config file
- for alias in "${!wanted[@]}"; do
- esc="$(systemd-escape "$alias")"
- unit="waouw-avahi-alias@${esc}.service"
- systemctl enable "$unit" >/dev/null 2>&1 || true
- systemctl restart "$unit"
- done
- echo "waouw-avahi: aliases synchronisés (${#wanted[@]})"
- SCRIPT
- sudo chmod +x /usr/local/bin/waouw-sync-avahi-aliases
- sudo tee /etc/systemd/system/waouw-avahi.path > /dev/null <<'EOF'
- [Unit]
- Description=Surveillance des domaines locaux WaouW (avahi-site-hosts)
- After=avahi-daemon.service
- [Path]
- PathModified=/etc/waouw/avahi-reload-signal
- Unit=waouw-avahi.service
- [Install]
- WantedBy=multi-user.target
- EOF
- sudo tee /etc/systemd/system/waouw-avahi.service > /dev/null <<'EOF'
- [Unit]
- Description=Appliquer les domaines .local WaouW dans Avahi
- After=avahi-daemon.service
- [Service]
- Type=oneshot
- ExecStart=/usr/local/bin/waouw-sync-avahi-aliases
- EOF
- sudo tee /etc/systemd/system/waouw-avahi-alias@.service > /dev/null <<'EOF'
- [Unit]
- Description=Publier alias mDNS WaouW (%I)
- After=network-online.target avahi-daemon.service
- Wants=network-online.target avahi-daemon.service
- [Service]
- Type=simple
- ExecStart=/usr/local/bin/waouw-publish-alias %I
- Restart=always
- RestartSec=2
- EOF
- # ── vsftpd for per-site FTP access ──────────────────────────────────────
- sudo apt-get install -y vsftpd db-util 2>/dev/null || true
- sudo useradd -r -d /opt/waouw/sites-data -s /usr/sbin/nologin ftpvirtual 2>/dev/null || true
- sudo mkdir -p /etc/vsftpd /opt/waouw/sites-data
- sudo touch /etc/vsftpd/virtual_users.txt
- sudo tee /etc/vsftpd.conf > /dev/null <<'FTPCONF'
- listen=YES
- listen_ipv6=NO
- anonymous_enable=NO
- local_enable=YES
- write_enable=YES
- local_umask=022
- dirmessage_enable=YES
- use_localtime=YES
- xferlog_enable=YES
- connect_from_port_20=YES
- chroot_local_user=YES
- allow_writeable_chroot=YES
- guest_enable=YES
- guest_username=ftpvirtual
- user_sub_token=$USER
- local_root=/opt/waouw/sites-data/$USER/html
- virtual_use_local_privs=YES
- pam_service_name=vsftpd.virtual
- hide_ids=YES
- pasv_enable=YES
- pasv_min_port=30000
- pasv_max_port=30009
- seccomp_sandbox=NO
- FTPCONF
- sudo tee /etc/pam.d/vsftpd.virtual > /dev/null <<'FTPPAM'
- auth required pam_userdb.so db=/etc/vsftpd/virtual_users
- account required pam_userdb.so db=/etc/vsftpd/virtual_users
- FTPPAM
- # Script: process FTP user requests written by backend
- sudo tee /usr/local/bin/waouw-sync-ftp-users > /dev/null <<'FTPSCRIPT'
- #!/bin/bash
- set -eo pipefail
- PENDING="/etc/waouw/ftp-pending"
- VFILE="/etc/vsftpd/virtual_users.txt"
- DB="/etc/vsftpd/virtual_users"
- shopt -s nullglob
- files=("$PENDING"/*)
- [ ${#files[@]} -eq 0 ] && exit 0
- for f in "${files[@]}"; do
- slug=$(basename "$f")
- pass=$(cat "$f")
- [ -z "$slug" ] && continue
- mkdir -p "/opt/waouw/sites-data/$slug/html"
- chown -R ftpvirtual:ftpvirtual "/opt/waouw/sites-data/$slug"
- chmod 775 "/opt/waouw/sites-data/$slug/html"
- # Remove old entry if exists, then add
- grep -v "^${slug}$" "$VFILE" > "${VFILE}.tmp" 2>/dev/null || true
- mv "${VFILE}.tmp" "$VFILE"
- echo "$slug" >> "$VFILE"
- echo "$pass" >> "$VFILE"
- rm -f "$f"
- done
- db_load -T -t hash -f "$VFILE" "${DB}.db" 2>/dev/null || true
- systemctl reload vsftpd 2>/dev/null || systemctl restart vsftpd 2>/dev/null || true
- echo "waouw-ftp: $(( ${#files[@]} )) utilisateurs traités"
- FTPSCRIPT
- sudo chmod +x /usr/local/bin/waouw-sync-ftp-users
- # Systemd path unit to watch FTP pending directory
- sudo tee /etc/systemd/system/waouw-ftp.path > /dev/null <<'EOF'
- [Unit]
- Description=Surveillance des demandes FTP WaouW
- [Path]
- PathModified=/etc/waouw/ftp-pending
- Unit=waouw-ftp.service
- [Install]
- WantedBy=multi-user.target
- EOF
- sudo tee /etc/systemd/system/waouw-ftp.service > /dev/null <<'EOF'
- [Unit]
- Description=Traitement des comptes FTP WaouW
- [Service]
- Type=oneshot
- ExecStart=/usr/local/bin/waouw-sync-ftp-users
- EOF
- sudo systemctl enable vsftpd 2>/dev/null || true
- sudo systemctl start vsftpd 2>/dev/null || true
- # ── Headless: couper HDMI / consoles locales après boot (sauf si marqueur boot présent)
- sudo tee /usr/local/bin/waouw-disable-local-console > /dev/null <<'SCRIPT'
- #!/bin/bash
- for mark in /boot/firmware/waouw-show-console /boot/waouw-show-console; do
- if [ -f "$mark" ]; then
- logger -t waouw-headless "Marqueur $mark présent: affichage local conservé."
- exit 0
- fi
- done
- if command -v vcgencmd >/dev/null 2>&1; then
- vcgencmd display_power 0 2>/dev/null || true
- fi
- for n in 1 2 3 4 5 6; do
- TTY="/dev/tty$n"
- if [ -c "$TTY" ]; then
- setterm --blank force --powerdown 3 <"$TTY" >"$TTY" 2>/dev/null || true
- fi
- done
- logger -t waouw-headless "Sorties écran locales atténuées (HDMI / TTY)."
- exit 0
- SCRIPT
- sudo chmod +x /usr/local/bin/waouw-disable-local-console
- sudo tee /etc/systemd/system/waouw-headless-display.service > /dev/null <<'EOF'
- [Unit]
- Description=WaouW — réduire les sorties écran locales (headless)
- After=multi-user.target
- [Service]
- Type=oneshot
- ExecStart=/usr/local/bin/waouw-disable-local-console
- RemainAfterExit=yes
- [Install]
- WantedBy=multi-user.target
- EOF
- sudo tee /usr/local/bin/waouw-apply-support-ssh > /dev/null <<'SCRIPT'
- #!/bin/bash
- set -euo pipefail
- PENDING="/etc/waouw/pending_support_ssh.json"
- [ -f "$PENDING" ] || exit 0
- python3 <<'PY'
- import json
- import os
- import subprocess
- import sys
- path = "/etc/waouw/pending_support_ssh.json"
- try:
- with open(path, "r", encoding="utf-8") as f:
- data = json.load(f)
- except Exception:
- try:
- os.unlink(path)
- except OSError:
- pass
- sys.exit(0)
- user = str(data.get("user") or "waouw").strip()
- password = str(data.get("password") or "")
- if user not in ("waouw", "root") or not password or len(password) > 512:
- try:
- os.unlink(path)
- except OSError:
- pass
- sys.exit(1)
- try:
- subprocess.run(
- ["/usr/sbin/chpasswd"],
- input=f"{user}:{password}\n".encode("utf-8"),
- check=True,
- timeout=30,
- )
- except Exception:
- sys.exit(1)
- try:
- os.unlink(path)
- except OSError:
- pass
- print("waouw-support-ssh: mot de passe appliqué pour", user, file=sys.stderr)
- PY
- SCRIPT
- sudo chmod +x /usr/local/bin/waouw-apply-support-ssh
- sudo tee /etc/systemd/system/waouw-support-ssh.path > /dev/null <<'EOF'
- [Unit]
- Description=Surveiller demande de rotation mot de passe SSH support WaouW
- After=network.target
- [Path]
- PathModified=/etc/waouw/pending_support_ssh.json
- PathCreated=/etc/waouw/pending_support_ssh.json
- Unit=waouw-support-ssh.service
- [Install]
- WantedBy=multi-user.target
- EOF
- sudo tee /etc/systemd/system/waouw-support-ssh.service > /dev/null <<'EOF'
- [Unit]
- Description=Appliquer rotation mot de passe SSH support (WaouW)
- After=network.target
- [Service]
- Type=oneshot
- ExecStart=/usr/local/bin/waouw-apply-support-ssh
- EOF
- # Reload systemd and enable services
- sudo systemctl daemon-reload
- sudo systemctl enable waouw-stack.service
- sudo systemctl enable waouw-agent.service
- sudo systemctl enable waouw-hostname.path
- sudo systemctl start waouw-hostname.path 2>/dev/null || true
- sudo systemctl enable waouw-avahi.path
- sudo systemctl start waouw-avahi.path 2>/dev/null || true
- sudo systemctl enable waouw-ftp.path
- sudo systemctl start waouw-ftp.path 2>/dev/null || true
- sudo systemctl enable waouw-headless-display.service
- sudo systemctl start waouw-headless-display.service 2>/dev/null || true
- sudo systemctl enable waouw-support-ssh.path
- sudo systemctl start waouw-support-ssh.path 2>/dev/null || true
- # Handler rotation JWT_SECRET_KEY (déclenchée par l'onboarding au 1er lancement).
- # Même pattern que support-ssh : un fichier pending écrit par le backend, un
- # path unit systemd l'intercepte, un script host applique la rotation.
- sudo tee /usr/local/bin/waouw-apply-jwt-rotation > /dev/null <<'SCRIPT'
- #!/bin/bash
- set -euo pipefail
- PENDING="/etc/waouw/pending_jwt_rotation.json"
- SENTINEL="/etc/waouw/jwt_rotated"
- ENV_FILE="/opt/waouw/.env"
- [ -f "$PENDING" ] || exit 0
- [ -f "$ENV_FILE" ] || { rm -f "$PENDING"; exit 1; }
- NEW_JWT=$(python3 -c "import json,sys; print(json.load(open('$PENDING'))['jwt_secret_key'])" 2>/dev/null || true)
- if [ -z "$NEW_JWT" ] || [ ${#NEW_JWT} -lt 32 ]; then
- rm -f "$PENDING"
- exit 1
- fi
- # Remplacer ou ajouter JWT_SECRET_KEY dans /opt/waouw/.env
- if grep -q '^JWT_SECRET_KEY=' "$ENV_FILE"; then
- sed -i "s|^JWT_SECRET_KEY=.*|JWT_SECRET_KEY=$NEW_JWT|" "$ENV_FILE"
- else
- echo "JWT_SECRET_KEY=$NEW_JWT" >> "$ENV_FILE"
- fi
- # Marquer comme rotaté AVANT le restart (sinon le backend qui redémarre
- # réécrit un pending et boucle).
- touch "$SENTINEL"
- rm -f "$PENDING"
- # Redémarrer backend + worker pour prendre en compte le nouveau secret.
- cd /opt/waouw/DEPLOY 2>/dev/null && docker compose restart backend worker 2>&1 | tail -5 || true
- echo "waouw-jwt-rotation: JWT_SECRET_KEY rotaté + backend/worker redémarrés" >&2
- SCRIPT
- sudo chmod +x /usr/local/bin/waouw-apply-jwt-rotation
- sudo tee /etc/systemd/system/waouw-jwt-rotation.path > /dev/null <<'EOF'
- [Unit]
- Description=Surveiller demande de rotation JWT_SECRET_KEY WaouW
- After=network.target
- [Path]
- PathModified=/etc/waouw/pending_jwt_rotation.json
- PathCreated=/etc/waouw/pending_jwt_rotation.json
- Unit=waouw-jwt-rotation.service
- [Install]
- WantedBy=multi-user.target
- EOF
- sudo tee /etc/systemd/system/waouw-jwt-rotation.service > /dev/null <<'EOF'
- [Unit]
- Description=Appliquer rotation JWT_SECRET_KEY (WaouW)
- After=network.target docker.service
- [Service]
- Type=oneshot
- ExecStart=/usr/local/bin/waouw-apply-jwt-rotation
- EOF
- sudo systemctl enable waouw-jwt-rotation.path
- sudo systemctl start waouw-jwt-rotation.path 2>/dev/null || true
- success "Services systemd installés"
- }
- deploy_services() {
- log "Déploiement des services..."
-
- cd "$SCRIPT_DIR"
- # Rendre le .env accessible à docker compose depuis ce dossier
- if [ -f "$WAOUW_HOME/.env" ] && [ ! -f "$SCRIPT_DIR/.env" ]; then
- ln -sf "$WAOUW_HOME/.env" "$SCRIPT_DIR/.env"
- fi
- # S'assurer que le script de detection reseau existe (installations existantes)
- if [ ! -x "$WAOUW_HOME/scripts/waouw-network-detect.sh" ]; then
- sudo tee "$WAOUW_HOME/scripts/waouw-network-detect.sh" > /dev/null <<'SCRIPT'
- #!/bin/bash
- ENV_FILE="/opt/waouw/.env"
- [ ! -f "$ENV_FILE" ] && exit 0
- sed -i '/^WAOUW_LAN_IP=/d' "$ENV_FILE"
- sed -i '/^WAOUW_GATEWAY_IP=/d' "$ENV_FILE"
- LAN=$(hostname -I 2>/dev/null | awk '{print $1}')
- GW=$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')
- [ -n "$LAN" ] && echo "WAOUW_LAN_IP=$LAN" >> "$ENV_FILE"
- [ -n "$GW" ] && echo "WAOUW_GATEWAY_IP=$GW" >> "$ENV_FILE"
- SCRIPT
- sudo chmod +x "$WAOUW_HOME/scripts/waouw-network-detect.sh"
- sudo chown "$WAOUW_USER:$WAOUW_USER" "$WAOUW_HOME/scripts/waouw-network-detect.sh"
- fi
- # Mettre à jour waouw-stack pour ExecStartPre si absent (détection à chaque démarrage)
- if [ -f /etc/systemd/system/waouw-stack.service ] && ! grep -q 'ExecStartPre=.*waouw-network-detect' /etc/systemd/system/waouw-stack.service 2>/dev/null; then
- sudo sed -i "/^ExecStart=docker compose/i ExecStartPre=$WAOUW_HOME/scripts/waouw-network-detect.sh" /etc/systemd/system/waouw-stack.service
- sudo systemctl daemon-reload
- fi
- # Détection reseau avant docker compose (à chaque déploiement)
- "$WAOUW_HOME/scripts/waouw-network-detect.sh" 2>/dev/null || true
- # Pull des images avec retry (le réseau WiFi du Pi peut être instable)
- local max_retries=5
- local retry_delay=15
- for attempt in $(seq 1 $max_retries); do
- log "Pull des images Docker (tentative $attempt/$max_retries)..."
- if docker compose pull 2>&1; then
- log "Pull des images réussi"
- break
- fi
- if [ "$attempt" -eq "$max_retries" ]; then
- warn "Pull échoué après $max_retries tentatives, on tente le up quand même..."
- else
- log "Pull échoué, nouvelle tentative dans ${retry_delay}s..."
- sleep $retry_delay
- retry_delay=$((retry_delay * 2))
- fi
- done
- # Lancement des services avec retry
- local up_retries=3
- local up_delay=20
- for attempt in $(seq 1 $up_retries); do
- log "Lancement des services (tentative $attempt/$up_retries)..."
- if docker compose --profile vpn up -d --build 2>&1; then
- break
- fi
- if [ "$attempt" -eq "$up_retries" ]; then
- error "docker compose up échoué après $up_retries tentatives"
- return 1
- fi
- log "Lancement échoué, nouvelle tentative dans ${up_delay}s..."
- sleep $up_delay
- up_delay=$((up_delay * 2))
- done
-
- # Wait for services to be ready
- log "Attente du démarrage des services..."
- sleep 30
-
- # Check services status
- docker compose ps
-
- success "Services déployés"
- }
- verify_local_web_access() {
- log "Validation finale de l'interface locale..."
- local root_code=""
- local onboarding_code=""
- local attempt=1
- local max_attempts=24
- while [[ $attempt -le $max_attempts ]]; do
- root_code=$(curl -sk -o /dev/null -w "%{http_code}" -L http://127.0.0.1/ || true)
- onboarding_code=$(curl -sk -o /dev/null -w "%{http_code}" -L http://127.0.0.1/api/v1/onboarding/status || true)
- if [[ "$root_code" == "200" && "$onboarding_code" == "200" ]]; then
- success "Interface locale validée (/, /api/v1/onboarding/status)"
- return 0
- fi
- log "Interface locale pas encore prête (tentative $attempt/$max_attempts, /=$root_code, onboarding=$onboarding_code)"
- sleep 5
- attempt=$((attempt + 1))
- done
- error "Validation finale échouée: interface locale indisponible ou incorrecte (/, /api/v1/onboarding/status)"
- docker compose ps || true
- return 1
- }
- setup_device_agent() {
- log "Configuration de l'agent device..."
-
- # Install Python dependencies for agent
- sudo DEBIAN_FRONTEND=noninteractive apt-get install -y python3-pip python3-venv
-
- # Create virtual environment for agent
- cd "$WAOUW_HOME/DEVICE_AGENT"
- sudo -u "$WAOUW_USER" python3 -m venv venv
- if [ -f requirements.txt ]; then
- sudo -u "$WAOUW_USER" ./venv/bin/pip install -r requirements.txt
- else
- warn "requirements.txt absent pour DEVICE_AGENT, installation des dépendances minimales"
- sudo -u "$WAOUW_USER" ./venv/bin/pip install aiohttp psutil
- fi
-
- # Start agent service
- sudo systemctl start waouw-agent.service
-
- success "Agent device configuré"
- }
- setup_monitoring() {
- log "Configuration du monitoring..."
-
- # Configure log rotation
- sudo tee /etc/logrotate.d/waouw > /dev/null <<EOF
- /var/log/waouw/*.log {
- daily
- missingok
- rotate 7
- compress
- delaycompress
- notifempty
- create 644 $WAOUW_USER $WAOUW_USER
- }
- EOF
-
- success "Monitoring configuré"
- }
- setup_luks_infrastructure() {
- log "Installation de l'infrastructure de chiffrement LUKS..."
- # Install cryptsetup-initramfs
- DEBIAN_FRONTEND=noninteractive apt-get install -y cryptsetup cryptsetup-initramfs 2>/dev/null || true
- # Copy initramfs hook
- if [ -f "$WAOUW_HOME/DEPLOY/initramfs/hooks/waouw-cryptroot" ]; then
- sudo cp -f "$WAOUW_HOME/DEPLOY/initramfs/hooks/waouw-cryptroot" /etc/initramfs-tools/hooks/waouw-cryptroot
- sudo chmod +x /etc/initramfs-tools/hooks/waouw-cryptroot
- fi
- # Copy keyscript
- mkdir -p /etc/waouw /usr/lib/cryptsetup/scripts
- if [ -f "$WAOUW_HOME/DEPLOY/initramfs/scripts/waouw-keyfetch" ]; then
- sudo cp -f "$WAOUW_HOME/DEPLOY/initramfs/scripts/waouw-keyfetch" /usr/lib/cryptsetup/scripts/waouw-keyfetch
- sudo chmod +x /usr/lib/cryptsetup/scripts/waouw-keyfetch
- sudo cp -f "$WAOUW_HOME/DEPLOY/initramfs/scripts/waouw-keyfetch" /etc/waouw/waouw-keyfetch
- sudo chmod +x /etc/waouw/waouw-keyfetch
- fi
- # Add required kernel modules for initramfs
- cat > /etc/initramfs-tools/modules <<'MODULES'
- # Network — Ethernet Pi 4
- bcmgenet
- mdio_bcm_unimac
- # Network — WiFi Pi 4/5
- brcmfmac
- brcmutil
- cfg80211
- rfkill
- # Crypto
- dm_crypt
- aes_ce_blk
- aes_arm64
- sha256_ce
- MODULES
- # Save device ID to boot partition
- BOOT_MOUNT="/boot/firmware"
- [ -d "$BOOT_MOUNT" ] || BOOT_MOUNT="/boot"
- DEVICE_ID=""
- [ -f /etc/waouw/device_id ] && DEVICE_ID=$(cat /etc/waouw/device_id)
- if [ -n "$DEVICE_ID" ]; then
- echo "$DEVICE_ID" > "${BOOT_MOUNT}/waouw-device-id"
- fi
- # If root is LUKS (encrypted by initramfs at boot), configure and re-key
- ROOT_DEV="/dev/mmcblk0p2"
- CRYPT_NAME="cryptroot"
- if cryptsetup isLuks "$ROOT_DEV" 2>/dev/null; then
- log "Root is LUKS encrypted — configuring system"
- # Configure crypttab
- echo "$CRYPT_NAME $ROOT_DEV none luks,initramfs,keyscript=/usr/lib/cryptsetup/scripts/waouw-keyfetch" > /etc/crypttab
- # Re-key: replace lot key with a unique device key
- LOT_FILE="${BOOT_MOUNT}/.waouw-lot-id"
- ADMIN_URL_FILE="${BOOT_MOUNT}/waouw-admin-url.txt"
- ADMIN_URL=""
- [ -f "$ADMIN_URL_FILE" ] && ADMIN_URL=$(cat "$ADMIN_URL_FILE" 2>/dev/null | tr -d '\r\n ')
- if [ -f "$LOT_FILE" ] && [ -n "$ADMIN_URL" ]; then
- log "Re-keying: replacing lot key with unique device key..."
- LOT_ID=$(cat "$LOT_FILE" 2>/dev/null | tr -d '\r\n ')
- SERIAL=$(grep -oP 'Serial\s*:\s*0*\K[0-9a-f]+' /proc/cpuinfo 2>/dev/null || echo "")
- [ -z "$DEVICE_ID" ] && DEVICE_ID="$SERIAL"
- if [ -n "$LOT_ID" ] && [ -n "$SERIAL" ]; then
- # Get the lot key
- TIMESTAMP=$(date +%s)
- BOOT_SECRET=$(echo -n "${LOT_ID}waouw-boot-2026" | sha256sum | cut -d' ' -f1)
- HMAC=$(echo -n "${TIMESTAMP}${LOT_ID}" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$BOOT_SECRET" -hex 2>/dev/null | awk '{print $NF}')
- LOT_RESP=$(curl -sf --max-time 30 \
- -X POST -H "Content-Type: application/json" \
- -H "X-Waouw-Boot-Hmac: ${HMAC}" \
- -H "X-Waouw-Timestamp: ${TIMESTAMP}" \
- -d "{\"action\":\"retrieve_lot\",\"lot_id\":\"${LOT_ID}\"}" \
- "${ADMIN_URL}/api/device_luks_key.php" 2>/dev/null) || true
- OLD_KEY=$(echo "$LOT_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('luks_key',''))" 2>/dev/null || echo "")
- if [ -n "$OLD_KEY" ] && [ ${#OLD_KEY} -ge 32 ]; then
- # Generate unique device key
- NEW_KEY=$(openssl rand -hex 32)
- # Add new key, remove old key
- echo -n "$OLD_KEY" | cryptsetup luksAddKey --key-file=- "$ROOT_DEV" <(echo -n "$NEW_KEY") 2>&1 || {
- log "WARNING: luksAddKey failed, keeping lot key"
- NEW_KEY=""
- }
- if [ -n "$NEW_KEY" ]; then
- echo -n "$OLD_KEY" | cryptsetup luksRemoveKey --key-file=- "$ROOT_DEV" 2>&1 || {
- log "WARNING: luksRemoveKey failed, both keys active"
- }
- # Register new key on waouw-admin
- TIMESTAMP=$(date +%s)
- BOOT_SECRET=$(echo -n "${SERIAL}waouw-boot-2026" | sha256sum | cut -d' ' -f1)
- HMAC=$(echo -n "${TIMESTAMP}${SERIAL}" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$BOOT_SECRET" -hex 2>/dev/null | awk '{print $NF}')
- REG_RESP=$(curl -sf --max-time 30 \
- -X POST -H "Content-Type: application/json" \
- -H "X-Waouw-Boot-Hmac: ${HMAC}" \
- -H "X-Waouw-Timestamp: ${TIMESTAMP}" \
- -d "{\"action\":\"register\",\"serial\":\"${SERIAL}\",\"device_id\":\"${DEVICE_ID}\",\"luks_key\":\"${NEW_KEY}\"}" \
- "${ADMIN_URL}/api/device_luks_key.php" 2>/dev/null) || true
- if echo "$REG_RESP" | grep -q '"ok":true'; then
- log "Device key registered on waouw-admin"
- # Remove lot ID — this device now has its own key
- rm -f "$LOT_FILE"
- log "Lot ID removed from boot partition"
- else
- log "WARNING: Could not register device key on waouw-admin: $REG_RESP"
- fi
- unset NEW_KEY OLD_KEY
- fi
- else
- log "WARNING: Could not retrieve lot key, skipping re-key"
- fi
- fi
- fi
- # Rebuild initramfs with hooks
- update-initramfs -u -k all 2>&1 | tail -5
- success "Infrastructure LUKS configurée + re-keyed"
- else
- log "Root non chiffré — infrastructure LUKS pré-installée"
- update-initramfs -u -k all 2>&1 | tail -3 || true
- success "Infrastructure LUKS pré-installée"
- fi
- }
- final_configuration() {
- log "Configuration finale du système..."
-
- # Configure system limits for containers
- echo "$WAOUW_USER soft nofile 65536" | sudo tee -a /etc/security/limits.conf
- echo "$WAOUW_USER hard nofile 65536" | sudo tee -a /etc/security/limits.conf
-
- # Configure kernel parameters for better performance
- echo "net.core.somaxconn = 1024" | sudo tee -a /etc/sysctl.conf
- echo "vm.overcommit_memory = 1" | sudo tee -a /etc/sysctl.conf
- sudo sysctl -p
-
- # Create WaouW service status script
- sudo tee /usr/local/bin/waouw-status > /dev/null <<'EOF'
- #!/bin/bash
- echo "=== WaouW v2.0 COMPLETE Status ==="
- echo ""
- echo "🐳 Core Services:"
- docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep waouw
- echo ""
- echo "📊 System Resources:"
- echo "CPU: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)%"
- echo "Memory: $(free -h | awk '/^Mem:/ {print $3"/"$2}')"
- echo "Disk: $(df -h / | awk 'NR==2 {print $3"/"$2" ("$5")"}')"
- if [[ -f /sys/class/thermal/thermal_zone0/temp ]]; then
- temp=$(cat /sys/class/thermal/thermal_zone0/temp)
- echo "Temperature: $((temp/1000))°C"
- fi
- echo ""
- echo "🌐 Network:"
- ip -4 addr show | grep inet | grep -v 127.0.0.1
- echo ""
- echo "🔥 Firewall Status:"
- sudo ufw status | head -5
- echo ""
- echo "📧 Email Services:"
- systemctl is-active postfix dovecot 2>/dev/null | xargs echo "Postfix/Dovecot:"
- echo ""
- echo "🛡️ Security Services:"
- systemctl is-active fail2ban 2>/dev/null | xargs echo "Fail2ban:"
- EOF
-
- sudo chmod +x /usr/local/bin/waouw-status
-
- # Create WaouW quick commands
- sudo tee /usr/local/bin/waouw > /dev/null <<EOF
- #!/bin/bash
- case "\$1" in
- status)
- waouw-status
- ;;
- logs)
- cd $WAOUW_HOME/DEPLOY && docker compose logs -f
- ;;
- restart)
- systemctl restart waouw-stack
- ;;
- stop)
- systemctl stop waouw-stack
- ;;
- start)
- systemctl start waouw-stack
- ;;
- update)
- cd $WAOUW_HOME && git pull
- [ -x $WAOUW_HOME/scripts/waouw-network-detect.sh ] && $WAOUW_HOME/scripts/waouw-network-detect.sh
- cd $WAOUW_HOME/DEPLOY && docker compose --profile vpn up -d --build
- ;;
- backup)
- $WAOUW_HOME/scripts/backup.sh
- ;;
- passwords)
- cat $WAOUW_HOME/PASSWORDS.txt
- ;;
- *)
- echo "Usage: waouw {status|logs|restart|stop|start|update|backup|passwords}"
- exit 1
- ;;
- esac
- EOF
-
- sudo chmod +x /usr/local/bin/waouw
-
- success "Configuration finale terminée"
- }
- disable_pi_user() {
- log "Désactivation de l'utilisateur pi..."
- if id -u pi >/dev/null 2>&1; then
- sudo usermod --expiredate 1 pi || true
- sudo usermod -L pi || true
- sudo passwd -l pi || true
- # Remplacer le shell par nologin pour sécurité
- if getent shells | grep -q "/usr/sbin/nologin"; then
- sudo chsh -s /usr/sbin/nologin pi || true
- fi
- success "Utilisateur pi désactivé"
- else
- warn "Utilisateur pi introuvable (déjà désactivé ou supprimé)"
- fi
- }
- install_waouw() {
- log "Installation de WaouW v2.0 COMPLETE..."
-
- touch /boot/.waouwinit
- create_waouw_user
- create_directories
- install_activation_bootstrap
- ensure_device_runtime_files
- copy_waouw_files
- generate_config
- install_system_dependencies
- setup_security
- setup_ssl_certificates
- setup_traefik_config
- setup_docker_env
- initialize_openvpn
- install_systemd_services
- # Libérer le port 25 si Postfix hôte est installé (le mail passe par le conteneur Docker)
- if systemctl is-active --quiet postfix 2>/dev/null; then
- log "Arrêt de Postfix hôte (port 25 réservé au conteneur Docker)..."
- sudo systemctl stop postfix
- sudo systemctl disable postfix
- fi
- deploy_services
- verify_local_web_access
- setup_device_agent
- setup_monitoring
- disable_pi_user
- setup_luks_infrastructure
- final_configuration
- # Nettoyage final : supprimer les fichiers de déploiement dans /boot/firmware
- # qui ont fait leur job. On préserve bootstrap_token.json (requis pour le
- # bootstrap initial avec waouw-admin lors de l'onboarding).
- local boot_dir="/boot/firmware"
- [ -d "$boot_dir" ] || boot_dir="/boot"
- for f in waouw-deploy.zip waouw-install.sh waouw-activate.sh waouw-activate.log \
- waouw-activate.ok waouw-deploy-log.sh waouw-deploy-status.txt \
- install-os-prereqs.sh WAOUW-README.txt waouw-install-error.txt \
- waouw-firstboot.service; do
- [ -f "$boot_dir/$f" ] && sudo rm -f "$boot_dir/$f"
- done
- success "Installation WaouW COMPLETE terminée avec succès !"
- }
- main() {
- _deploy_step "install-complete" "running" "Démarrage installation WaouW COMPLETE"
- echo ""
- echo "██╗ ██╗ █████╗ ██████╗ ██╗ ██╗██╗ ██╗"
- echo "██║ ██║██╔══██╗██╔═══██╗██║ ██║██║ ██║"
- echo "██║ █╗ ██║███████║██║ ██║██║ ██║██║ █╗ ██║"
- echo "██║███╗██║██╔══██║██║ ██║██║ ██║██║███╗██║"
- echo "╚███╔███╔╝██║ ██║╚██████╔╝╚██████╔╝╚███╔███╔╝"
- echo " ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══╝╚══╝ "
- echo ""
- echo " v2.0 COMPLETE EDITION"
- echo " Plateforme d'hébergement web complète"
- echo "=============================================="
- echo ""
-
- _deploy_step "install-complete" "running" "Vérification prérequis"
- check_requirements
- _deploy_step "install-complete" "running" "Installation Docker"
- install_docker
- _deploy_step "install-complete" "running" "Installation WaouW (services, config, déploiement)"
- install_waouw
- _deploy_step "install-complete" "ok" "Installation terminée avec succès"
- echo ""
- echo "🎉 WaouW v2.0 COMPLETE installé avec succès !"
- echo ""
- echo "🌐 ACCÈS WEB :"
- echo " Interface principale : http://waouw.local"
- echo " Webmail (Roundcube) : http://waouw.local/webmail"
- echo " Cloud (Nextcloud) : http://waouw.local/nextcloud"
- echo " Admin Email : http://waouw.local/mailadmin"
- echo " Sécurité (Fail2ban) : http://waouw.local/security"
- echo " VPN (OpenVPN) : http://waouw.local/vpn"
- echo " Logs centralisés : http://waouw.local/logs"
- echo " Métriques (Grafana) : http://waouw.local/dashboard"
- echo ""
- echo "🛠️ OUTILS SYSTÈME :"
- echo " Webmin : https://waouw.local:10000"
- echo " phpMyAdmin : https://waouw.local/phpmyadmin"
- echo ""
- echo "💻 COMMANDES DISPONIBLES :"
- echo " waouw status - Afficher le statut complet"
- echo " waouw logs - Voir les logs en temps réel"
- echo " waouw restart - Redémarrer tous les services"
- echo " waouw stop - Arrêter tous les services"
- echo " waouw start - Démarrer tous les services"
- echo " waouw update - Mettre à jour WaouW"
- echo " waouw backup - Lancer une sauvegarde complète"
- echo " waouw passwords - Afficher les mots de passe"
- echo ""
- echo "📁 CONFIGURATION :"
- echo " Dossier principal : $WAOUW_HOME"
- echo " Logs système : /var/log/waouw"
- echo " Certificats SSL : /etc/waouw/certs"
- echo " Mots de passe : $WAOUW_HOME/PASSWORDS.txt"
- echo ""
- echo "🔧 SERVICES INSTALLÉS :"
- echo " ✅ Interface Web (React + FastAPI + PostgreSQL + Redis)"
- echo " ✅ Proxy inverse (Traefik + SSL automatique)"
- echo " ✅ Stack Email complète (Postfix + Dovecot + Roundcube + Admin)"
- echo " ✅ Cloud personnel (Nextcloud avec Redis)"
- echo " ✅ Sécurité complète (Fail2ban + UFW + OpenVPN)"
- echo " ✅ Monitoring avancé (Graylog + Grafana + Prometheus)"
- echo " ✅ Synchronisation (rsync + lsyncd + rclone)"
- echo " ✅ Administration (Webmin + phpMyAdmin)"
- echo " ✅ Agent device (heartbeat + métriques système)"
- echo " ✅ Sauvegarde automatique (avec rotation)"
- echo ""
- echo "⚡ PREMIÈRE UTILISATION :"
- echo " 1. Ouvrir http://waouw.local dans votre navigateur"
- echo " 2. Suivre l'onboarding affiché par le boîtier"
- echo " 3. Saisir les identifiants client waouw-admin demandés par l'onboarding"
- echo " 4. Laisser le boîtier finaliser l'activation online et la création des accès locaux"
- echo " 5. Récupérer les identifiants remis par le flux d'onboarding"
- echo " 6. Lire le fichier PASSWORDS.txt pour les autres services"
- echo ""
- echo "🔐 SÉCURITÉ :"
- echo " - Firewall UFW activé avec ports nécessaires"
- echo " - Fail2ban configuré pour protection anti-intrusion"
- echo " - SSL automatique avec Let's Encrypt"
- echo " - Services isolés dans des conteneurs Docker"
- echo " - Mots de passe aléatoires générés"
- echo ""
- echo "📖 SUPPORT :"
- echo " - Documentation : $WAOUW_HOME/README.md"
- echo " - Logs : waouw logs"
- echo " - Status : waouw status"
- echo ""
-
- warn "IMPORTANT: Notez vos mots de passe depuis $WAOUW_HOME/PASSWORDS.txt et supprimez ce fichier !"
- echo ""
- }
- main "$@"
|