#!/bin/sh
# p2i-profil — applique un profil d'usage à ce poste.
#
#   sudo p2i-profil perso    poste personnel : mises à jour de sécurité
#                            automatiques, pas d'outil d'assistance
#   sudo p2i-profil client   poste client : toutes les mises à jour
#                            automatiques, pare-feu actif, assistance à distance
#   p2i-profil               affiche le profil en place
#
# Choisi dans l'installateur ; peut être relancé à tout moment.
set -eu

ETAT=/etc/p2i/profil
MAJ=/etc/apt/apt.conf.d/52p2i-mises-a-jour

if [ $# -eq 0 ]; then
    if [ -f "$ETAT" ]; then cat "$ETAT"; else echo "aucun"; fi
    exit 0
fi
profil="$1"
case "$profil" in
    perso|client) ;;
    *) echo "Usage : p2i-profil [perso|client]" >&2; exit 2 ;;
esac
[ "$(id -u)" -eq 0 ] || { echo "À lancer en root : sudo p2i-profil $profil" >&2; exit 1; }
export DEBIAN_FRONTEND=noninteractive

# Vérification quotidienne + installation automatique (les deux profils)
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'APT'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT

# Outil d'assistance installé (P2i Assistance ou RustDesk) : paquet, commande, service
ASSIST_PAQUET=""; ASSIST_CMD=""; ASSIST_SERVICE=""
if infos="$(/usr/libexec/p2i/assistance-outil 2>/dev/null)"; then
    ASSIST_PAQUET="$(printf '%s\n' "$infos" | sed -n 1p)"
    ASSIST_CMD="$(printf '%s\n' "$infos" | sed -n 2p)"
    ASSIST_SERVICE="$(printf '%s\n' "$infos" | sed -n 3p)"
fi

case "$profil" in
perso)
    # Par défaut Ubuntu n'installe seul que les correctifs de sécurité
    rm -f "$MAJ"
    if [ -n "$ASSIST_PAQUET" ]; then
        systemctl disable "$ASSIST_SERVICE" 2>/dev/null || true
        apt-get -y purge "$ASSIST_PAQUET" || true
        rm -f "/usr/lib/systemd/system/$ASSIST_SERVICE" "/usr/bin/$ASSIST_CMD"
    fi
    ;;
client)
    # En plus de la sécurité : mises à jour courantes et navigateur,
    # nettoyage des anciens noyaux, jamais de redémarrage imposé.
    cat > "$MAJ" <<'APT'
Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}-updates";
};
Unattended-Upgrade::Origins-Pattern {
    "site=packages.mozilla.org";
};
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
APT
    # Pare-feu : connexions entrantes refusées par défaut
    if [ -f /etc/ufw/ufw.conf ]; then
        sed -i 's/^ENABLED=.*/ENABLED=yes/' /etc/ufw/ufw.conf
        systemctl enable ufw.service 2>/dev/null || true
    fi
    if [ -n "$ASSIST_PAQUET" ]; then
        systemctl enable "$ASSIST_SERVICE" 2>/dev/null || true
    fi
    ;;
esac

mkdir -p /etc/p2i
echo "$profil" > "$ETAT"
echo "Profil appliqué : $profil"
