#!/bin/sh

set -eu
export LC_ALL=C

SELF=${0##*/}
GRUB_CFG=/boot/grub/grub.cfg
GRUB_ENV=/boot/grub/grubenv
ACCOUNT_FILE=/var/lib/AccountsService/users/unbee
LIGHTDM_CONFIG=/etc/lightdm/lightdm.conf
GROW_ROOTFS_URL=https://scripts.unbee.fr/grow-rootfs.sh
CREATE_SWAPFILE_URL=https://scripts.unbee.fr/create-swapfile.sh
WALLPAPER_URL=https://www.unbee.fr/wp-content/uploads/2025/04/fond-ecran-linux-mint.png
WALLPAPER_43_URL=https://www.unbee.fr/wp-content/uploads/2024/05/fond-ecran-4-3-bleu.jpg

usage() {
    cat <<-EOF
	Utilisation :
	  sudo $SELF

	Propose successivement plusieurs actions d'initialisation du système.
	Chaque action peut être exécutée ou sautée indépendamment.
	EOF
}

die() {
    printf 'Erreur : %s\n' "$*" >&2
    exit 1
}

run_action() {
    ra_title=$1
    ra_function=$2

    printf '\n' >/dev/tty
    while :; do
        printf '%s ? [O/n] ' "$ra_title" >/dev/tty
        IFS= read -r ra_answer </dev/tty || die "impossible de lire la réponse"
        case "$ra_answer" in
            ''|o|O|oui|Oui|OUI)
                "$ra_function"
                return
                ;;
            n|N|non|Non|NON)
                return
                ;;
            *)
                printf 'Répondre par oui ou non.\n' >/dev/tty
                ;;
        esac
    done
}

show_grub_menu() {
    command -v grub-editenv >/dev/null 2>&1 || \
        die "commande requise absente : grub-editenv"
    [ -f "$GRUB_ENV" ] || die "fichier absent : $GRUB_ENV"

    grub-editenv "$GRUB_ENV" set recordfail=1
}

rename_grub_entries() {
	echo 'Une mise à jour rétablira les libellés produits par la configuration GRUB.'
    [ -f "$GRUB_CFG" ] || die "fichier absent : $GRUB_CFG"

    sed -i \
        -e '/^[[:space:]]*menuentry[[:space:]]/s/Ubuntu/Linux Mint/g' \
        -e '/^[[:space:]]*submenu[[:space:]]/s/Ubuntu/Linux Mint/g' \
        "$GRUB_CFG"
}

download_unbee_wallpaper() {
    command -v xdg-user-dir >/dev/null 2>&1 || \
        die "commande requise absente : xdg-user-dir"
    duw_home=$(getent passwd unbee | awk -F: '$1 == "unbee" { print $6; exit }')
    [ -n "$duw_home" ] || die "compte absent : unbee"
    duw_uid=$(id -u unbee)
    duw_gid=$(id -g unbee)
    duw_directory=$(HOME="$duw_home" \
        XDG_CONFIG_HOME="$duw_home/.config" xdg-user-dir PICTURES)
    [ -n "$duw_directory" ] || die "dossier d'images introuvable pour unbee"
    duw_wallpaper=$duw_directory/fond-ecran-linux-mint.png
    duw_wallpaper_43=$duw_directory/fond-ecran-4-3-bleu.jpg

    install -d -m 755 -o "$duw_uid" -g "$duw_gid" "$duw_directory"
    if ! curl -fsSL "$WALLPAPER_URL" -o "$duw_wallpaper"; then
        rm -f "$duw_wallpaper"
        die "échec du téléchargement de $WALLPAPER_URL"
    fi
    chown "$duw_uid:$duw_gid" "$duw_wallpaper"

    if ! curl -fsSL "$WALLPAPER_43_URL" -o "$duw_wallpaper_43"; then
        rm -f "$duw_wallpaper_43"
        die "échec du téléchargement de $WALLPAPER_43_URL"
    fi
    chown "$duw_uid:$duw_gid" "$duw_wallpaper_43"
}

hide_account() {
    [ -f "$ACCOUNT_FILE" ] || die "fichier absent : $ACCOUNT_FILE"

    sed -ri 's,(SystemAccount)=false,\1=true,' "$ACCOUNT_FILE"
}

enable_manual_login() {
    [ -d /etc/lightdm ] || die "répertoire absent : /etc/lightdm"
    [ -f "$LIGHTDM_CONFIG" ] || : >"$LIGHTDM_CONFIG"

    eml_tmp=$(mktemp /etc/lightdm/.lightdm.conf.XXXXXX)
    awk '
        BEGIN {
            in_seat = 0
            seat_seen = 0
            setting_written = 0
        }
        function write_setting() {
            if (!setting_written) {
                print "greeter-show-manual-login=true"
                setting_written = 1
            }
        }
        /^[[:space:]]*\[[^]]+\][[:space:]]*$/ {
            if (in_seat)
                write_setting()
            in_seat = ($0 ~ /^[[:space:]]*\[Seat:\*\][[:space:]]*$/)
            if (in_seat)
                seat_seen = 1
            print
            next
        }
        in_seat && /^[[:space:]]*#?[[:space:]]*greeter-show-manual-login[[:space:]]*=/ {
            write_setting()
            next
        }
        { print }
        END {
            if (in_seat)
                write_setting()
            if (!seat_seen) {
                print ""
                print "[Seat:*]"
                print "greeter-show-manual-login=true"
            }
        }
    ' "$LIGHTDM_CONFIG" 2>/dev/null >"$eml_tmp" || {
        rm -f "$eml_tmp"
        die "impossible de préparer $LIGHTDM_CONFIG"
    }
    cat "$eml_tmp" >"$LIGHTDM_CONFIG"
    rm -f "$eml_tmp"
}

change_hostname() {
    [ -f /etc/hostname ] || die "fichier absent : /etc/hostname"

    while :; do
        printf 'Nouveau nom : ' >/dev/tty
        IFS= read -r ch_new </dev/tty || die "impossible de lire le nouveau nom"
        case "$ch_new" in
            '')
                printf 'Le nom ne peut pas être vide.\n' >/dev/tty
                continue
                ;;
            *[!A-Za-z0-9-]*|-*|*-)
                printf 'Utiliser uniquement des lettres, des chiffres et des tirets.\n' >/dev/tty
                continue
                ;;
        esac
        [ "${#ch_new}" -le 63 ] || {
            printf 'Le nom ne peut pas dépasser 63 caractères.\n' >/dev/tty
            continue
        }
        break
    done

    printf '%s\n' "$ch_new" >/etc/hostname

    if [ -f /etc/hosts ]; then
        if grep -q '^[[:space:]]*127\.0\.1\.1[[:space:]]' /etc/hosts; then
            sed -ri \
                "s/^([[:space:]]*127\\.0\\.1\\.1[[:space:]]+)[^[:space:]]+/\\1$ch_new/" \
                /etc/hosts
        else
            printf '127.0.1.1\t%s\n' "$ch_new" >>/etc/hosts
        fi
    fi
}

configure_keyboard() {
    command -v dpkg-reconfigure >/dev/null 2>&1 || \
        die "commande requise absente : dpkg-reconfigure"

    dpkg-reconfigure keyboard-configuration </dev/tty >/dev/tty 2>&1
}

run_remote_script() {
    rrs_url=$1
    rrs_name=$2
    rrs_script=$(mktemp "/tmp/$rrs_name.XXXXXX")

    if ! curl -fsSL "$rrs_url" -o "$rrs_script"; then
        rm -f "$rrs_script"
        die "échec du téléchargement de $rrs_url"
    fi

    rrs_status=0
    sh "$rrs_script" || rrs_status=$?
    rm -f "$rrs_script"
    return "$rrs_status"
}

grow_rootfs() {
    run_remote_script "$GROW_ROOTFS_URL" grow-rootfs
}

create_swapfile() {
    run_remote_script "$CREATE_SWAPFILE_URL" create-swapfile
}

case "${1:-}" in
    -h|--help|help)
        usage
        exit 0
        ;;
esac

[ "$#" -eq 0 ] || {
    usage >&2
    exit 2
}

[ "$(id -u)" -eq 0 ] || die "ce script doit être lancé avec sudo ou en root"

CURRENT_HOSTNAME=$(sed -n '1{s/[[:space:]]*$//;p;}' /etc/hostname 2>/dev/null || :)
[ -n "$CURRENT_HOSTNAME" ] || CURRENT_HOSTNAME=inconnu

run_action "Afficher le menu GRUB au prochain démarrage" show_grub_menu
run_action "Remplacer « Ubuntu » par « Linux Mint » dans le menu GRUB" rename_grub_entries
run_action "Télécharger les fonds d’écran du compte unbee" download_unbee_wallpaper
run_action "Masquer le compte unbee" hide_account
run_action "Autoriser la connexion manuelle dans LightDM" enable_manual_login
run_action "Changer le nom de la machine (actuellement : $CURRENT_HOSTNAME)" change_hostname
run_action "Configurer la disposition du clavier" configure_keyboard
run_action "Agrandir la partition et le système de fichiers racine" grow_rootfs
run_action "Créer un fichier de swap de 4 Gio" create_swapfile
