#!/usr/bin/env bash
set -euo pipefail
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
CONFIG_FILE="/opt/microavia/config/node-ids.txt"
TARGET_USER="user"
TARGET_HOME="/home/${TARGET_USER}"
AUTOSTART_DIR="${TARGET_HOME}/.config/autostart"
AUTOSTART_FILE="${AUTOSTART_DIR}/microavia.desktop"
GDM_CONF_SRC="/usr/share/microavia-rc-setup/gdm3.conf"
DESKTOP_SRC="/usr/share/microavia-rc-setup/microavia.desktop"
GDM_CONF_DST="/etc/gdm3/custom.conf"

require_root() {
    if [ "${EUID}" -ne 0 ]; then
        echo "ERROR: setup-rc must be run as root." >&2
        exit 1
    fi
}

require_file() {
    if [ ! -f "$1" ]; then
        echo "ERROR: Missing required file: $1" >&2
        exit 1
    fi
}

set_gdm_key() {
    local key="$1"
    local value="$2"

    if grep -Eq "^[[:space:]]*${key}[[:space:]]*=" "${GDM_CONF_DST}"; then
        sed -i -E "s|^[[:space:]]*${key}[[:space:]]*=.*|${key} = ${value}|" "${GDM_CONF_DST}"
    else
        sed -i "/^\[daemon\]/a ${key} = ${value}" "${GDM_CONF_DST}"
    fi
}

require_root

echo "===== Microavia RC setup started ====="

# ------------------------------------------------
echo "[1/5] Creating node-ids.txt, device hostname, and modem identity"
# ------------------------------------------------
while true; do
    read -rp "Enter device serial number: " SERIAL
    [[ -n "${SERIAL}" ]] && break
    echo "Serial number cannot be empty."
done

while true; do
    read -rp "Enter modem NET-ID: " NET_ID
    [[ -n "${NET_ID}" ]] && break
    echo "NET-ID cannot be empty."
done

mkdir -p "$(dirname "${CONFIG_FILE}")"
cat > "${CONFIG_FILE}" <<EOF_RC
SERIAL ${SERIAL}
NET-ID ${NET_ID}
EOF_RC
chmod 0644 "${CONFIG_FILE}"

echo "Configuration saved to ${CONFIG_FILE}"

HOSTNAME="${SERIAL//./-}"
HOSTNAME="$(printf '%s' "${HOSTNAME}" | tr -cd '[:alnum:]-')"

if [ -z "${HOSTNAME}" ]; then
    echo "ERROR: Hostname became empty after sanitizing SERIAL: ${SERIAL}" >&2
    exit 1
fi

echo "Setting hostname to: ${HOSTNAME}"
hostnamectl set-hostname "${HOSTNAME}"

if grep -q '^127\.0\.1\.1' /etc/hosts; then
    sed -i "s/^127\.0\.1\.1.*/127.0.1.1\t${HOSTNAME}/" /etc/hosts
else
    printf '127.0.1.1\t%s\n' "${HOSTNAME}" >> /etc/hosts
fi

# ------------------------------------------------
echo "[2/5] Applying GDM auto-login configuration"
# ------------------------------------------------
require_file "${GDM_CONF_SRC}"
install -d -m 0755 /etc/gdm3

if [ ! -f "${GDM_CONF_DST}" ]; then
    install -m 0644 "${GDM_CONF_SRC}" "${GDM_CONF_DST}"
else
    if ! grep -q '^\[daemon\]' "${GDM_CONF_DST}"; then
        sed -i '1i [daemon]' "${GDM_CONF_DST}"
    fi
    set_gdm_key "AutomaticLoginEnable" "true"
    set_gdm_key "AutomaticLogin" "${TARGET_USER}"
fi
# ------------------------------------------------

echo "[3/5] Enable extensions and applying just-perfection settings"

if command -v gtk-update-icon-cache >/dev/null 2>&1; then
  gtk-update-icon-cache -q /usr/share/icons/hicolor || true
fi

flower-configure-gnome || true
# ------------------------------------------------
echo "[4/5] Installing Microavia desktop autostart for ${TARGET_USER}"
# ------------------------------------------------
require_file "${DESKTOP_SRC}"

if ! id "${TARGET_USER}" >/dev/null 2>&1; then
    echo "ERROR: Target user does not exist: ${TARGET_USER}" >&2
    exit 1
fi

install -d -o "${TARGET_USER}" -g "${TARGET_USER}" -m 0755 "${AUTOSTART_DIR}"
install -o "${TARGET_USER}" -g "${TARGET_USER}" -m 0644 "${DESKTOP_SRC}" "${AUTOSTART_FILE}"

# ------------------------------------------------
echo "[5/5] Enabling Microhard modem auto-cofiguration and services"
# ------------------------------------------------
systemctl daemon-reload
if ! command -v mh-setup &> /dev/null; then
    echo "microavia-microhard-tools is not installed."
    exit 1
else
    mh-setup --device rc
fi

if command -v nmcli >/dev/null 2>&1; then
    if ! nmcli -g NAME con show | grep -qx "microhard-lan"; then
        nmcli con add \
            type ethernet \
            ifname enp0s31f6 \
            con-name microhard-lan \
            ipv4.method manual \
            ipv4.addresses 192.168.168.5/24 \
            ipv4.gateway 192.168.168.1 \
            ipv6.method disabled \
            connection.autoconnect yes
    else
        echo "microhard-lan connection profile already exists, skipping"
    fi
else
    echo "ERROR: nmcli not found, cannot configure microhard-lan. Please fix issues and set it up manually" >&2
fi

systemctl enable --now ssh
systemctl enable microavia-radio-socat.service >/dev/null || true

# ------------------------------------------------
echo "===== RC setup complete. Restarting graphical login ====="

if systemctl is-active --quiet gdm3; then
    systemctl restart gdm3
else
    systemctl start gdm3
fi