#!/bin/sh
# DanOS Net Installing.
if [ ! "$(id -u)" -eq 0 ]; then
  echo "Login as the Root user and run the DanOS install again."
  su --login root
fi
#
# Gets the Username and Home directory.
NEW_USERHOME=$(grep ":1000:" /etc/passwd | cut -d: -f6)
NEW_USERNAME=$(grep ":1000:" /etc/passwd | cut -d: -f1)
#
export NEW_USERHOME
export NEW_USERNAME
#
# Add user-setup and first-login-user-setup, so that they can be added to as needed and run at the end and on first login.
echo "#!/usr/bin/env bash" >>"$NEW_USERHOME"/.first-login-user-setup
chmod +x "$NEW_USERHOME"/.first-login-user-setup
chown "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.first-login-user-setup
echo "#!/usr/bin/bash" >>"$NEW_USERHOME"/.user-setup
chmod +x "$NEW_USERHOME"/.user-setup
chown "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.user-setup
# User command
#runuser -l "$NEW_USERNAME" -c 'commands'
#
# Sudoers ------------------------------------------------------------------------------------------------------------------------------------
# Add User sudo NOPASSWD to shutdown now and reboot
echo "$NEW_USERNAME ALL=(ALL) NOPASSWD: /sbin/shutdown now, /sbin/reboot" | tee -a /etc/sudoers.d/"$NEW_USERNAME" && visudo -c -f /etc/sudoers.d/"$NEW_USERNAME"
#
# Set sudo password timeout
echo "Defaults timestamp_timeout=25" | tee -a /etc/sudoers.d/"$NEW_USERNAME" && visudo -c -f /etc/sudoers.d/"$NEW_USERNAME"
# -----------------------------------------------------------------------------------------------------------------------------------------
#
# Set Echo colors
# for c in {0..255}; do tput setaf $c; tput setaf $c | cat -v; echo =$c; done
# echo -e "${GREEN} TEXT ${NC}"
# shellcheck disable=SC2034
#NC="\033[0m"
# shellcheck disable=SC2034
#RED="\033[0;31m"
# shellcheck disable=SC2034
#GREEN="\033[0;32m"
#
# Function to check and exit on error use, check_error "TXT"
#
# Check if it's a Debian system installation and get the version codename.
# shellcheck disable=SC1091
if [ -f /etc/debian_version ]; then
  . /etc/os-release #Get the VERSION_CODENAME
  # shellcheck disable=SC2034
  VERSION_CODENAME_SHOULD_NOT_BE=codename-her
else
  echo "This installation should only be run on a Debian Linux System."
  echo "See more at https://git.itmail.dk/mara/danos/"
  exit 1
fi
#
# shellcheck disable=
echo " "
echo " "
echo "      Starting the DanOS installation"
echo "      See more info at https://git.itmail.dk/mara/danos/"
echo "      Enter your user password, to continue if necessary"
echo "      Or CTRL + C to cancel the installation"
echo " "
echo " "
#
check_error() {
  if [ $? -ne 0 ]; then
    echo "An error occurred during installation and has been stopped."
    echo "Or you have pressed CTRL + C to cancel."
    echo "$(date +"%d-%m-%Y %H:%M:%S") Error occurred during.: $1" | tee -a /root/log-danos-install.log
    exit 1
  fi
}
#
if [ -d /tmp/src/apt/ ]; then
  # Check and Copy APT Sources List
  if [ -f /etc/apt/sources.list ]; then
    mv /etc/apt/sources.list /etc/apt/old-type-sources.list.bak
  fi
  # Copy in new APT files
  cp -rfu /tmp/src/apt/* /etc/apt/
  check_error "Copy APT Sources list files"
  #Get the VERSION_CODENAME to determine changes to be made in APT source list.
  OS_VERSION_FOR_APT=$(lsb_release -cs)
  case "$OS_VERSION_FOR_APT" in
  bookworm)
    echo "Bookworm Detected."
    sed -i 's/APTLISTOS/bookworm/g' /etc/apt/sources.list.d/debian.sources
    sed -i 's/APTLISTOS/bookworm/g' /etc/apt/preferences.d/99apt-pin
    ;;
  trixie)
    echo "Trixie Detected."
    sed -i 's/APTLISTOS/trixie/g' /etc/apt/sources.list.d/debian.sources
    sed -i 's/APTLISTOS/trixie/g' /etc/apt/preferences.d/99apt-pin
    ;;
  forky)
    echo "Forky Detected."
    sed -i "s/Suites: APTLISTOS APTLISTOS-updates/Suites: sid trixie-updates/g" "/etc/apt/sources.list.d/debian.sources"
    sed -i "s/Suites: APTLISTOS-security/Suites: trixie-security/g" "/etc/apt/sources.list.d/debian.sources"
    sed -i 's/APTLISTOS/trixie/g' /etc/apt/preferences.d/99apt-pin
    ;;
  *)
    echo "Unknown Debian release: $OS_VERSION_FOR_APT.  Stop action taken."
    exit 1
    ;;
  esac
fi
check_error "Check and replace APT Sources list distro"
#
DEBIAN_FRONTEND=noninteractive apt update
DEBIAN_FRONTEND=noninteractive apt update
DEBIAN_FRONTEND=noninteractive apt -y upgrade
DEBIAN_FRONTEND=noninteractive apt -y autoremove
DEBIAN_FRONTEND=noninteractive apt -y autopurge
#
DEBIAN_FRONTEND=noninteractive apt -y install wget curl git ca-certificates build-essential extrepo
# extrepo add contrib, non-free and update
sed -i 's/# - contrib/- contrib/g; s/# - non-free/- non-free/g' /etc/extrepo/config.yaml
# Use "extrepo search" to find the repo name.
# Example.: extrepo enable REPO-NAME && extrepo enable REPO-NAME # the first one adds it to the repo list and the second one enables it
#
extrepo update
#
DEBIAN_FRONTEND=noninteractive apt -y --ignore-missing -t stable-backports install linux-image-amd64 linux-headers-amd64
#
# Xlibre repo
extrepo enable xlibre && extrepo enable xlibre && extrepo update
# Or the manual way.
#install -m 0755 -d /etc/apt/keyrings
#curl -fsSL https://xlibre-deb.github.io/key.asc | tee /etc/apt/keyrings/xlibre-deb.asc
#chmod a+r /etc/apt/keyrings/xlibre-deb.asc
#
# shellcheck disable=SC1091
#cat <<EOF | tee /etc/apt/sources.list.d/xlibre-deb.sources
#Types: deb deb-src
#URIs: https://xlibre-deb.github.io/debian/
#Suites: $(. /etc/os-release && echo "$VERSION_CODENAME")
#Components: main
#Architectures: $(dpkg --print-architecture)
#Signed-By: /etc/apt/keyrings/xlibre-deb.asc
#EOF
#
DEBIAN_FRONTEND=noninteractive apt update
#
# Xserver install.
# Check if the cpu is a QEMU Virtual CPU using lscpu
if lscpu | grep -iq "QEMU"; then
  echo "QEMU Virtual CPU detected. Installing xrdp and restarting service..."
  apt update
  DEBIAN_FRONTEND=noninteractive apt -y install xserver-xorg xserver-xorg-input-all picom arandr autorandr rofi xrdp xorgxrdp qemu-guest-agent xsecurelock xss-lock
  usermod -aG xrdp "$NEW_USERNAME"
  systemctl restart xrdp.service
  ufw allow 3389/tcp comment Remote_Desktop_Protocol
else
  DEBIAN_FRONTEND=noninteractive apt -y install xlibre picom arandr autorandr rofi xsecurelock xss-lock
  ln -s /usr/bin/Xorg /usr/lib/Xorg
fi
clear #Clear the screen
check_error "Install Xserver and Check if the CPU is a QEMU Virtual CPU and install xrdp"
#
DEBIAN_FRONTEND=noninteractive apt -y install bash-completion kitty bind9-dnsutils polkitd pkexec lxpolkit acl dbus-user-session adduser debconf lm-sensors dunst libnotify-bin notify-osd linux-cpupower power-profiles-daemon
#
DEBIAN_FRONTEND=noninteractive apt -y install build-essential dkms mokutil ufw gufw unzip cron openssh-server xdg-desktop-portal xdg-desktop-portal-gtk unattended-upgrades
#DEBIAN_FRONTEND=noninteractive apt -y install xdg-desktop-portal-wlr wofi
DEBIAN_FRONTEND=noninteractive apt -y install mc thunar gvfs gvfs-backends nsxiv mpv flameshot parted gparted mpd mpc ncmpcpp fzf ccrypt xarchiver notepadqq
DEBIAN_FRONTEND=noninteractive apt -y install colord mesa-utils htop btop tmux numlockx xdg-utils fancontrol xbacklight brightnessctl pm-utils ncdu less tealdeer
DEBIAN_FRONTEND=noninteractive apt -y install fwupd firmware-iwlwifi bluez-firmware
#
# Keyboard layouts, fonts, character sets and replacement tables for kbd / Keyboard
DEBIAN_FRONTEND=noninteractive apt -y install console-data
#
# libglib includes gsettings etc.
DEBIAN_FRONTEND=noninteractive apt -y install libglib2.0-bin
#
# a part of the Theming
DEBIAN_FRONTEND=noninteractive apt -y install lxappearance qt5ct qt6ct
#
check_error "APT Main Install"
#
# Network Share Components
DEBIAN_FRONTEND=noninteractive apt install -y ceph-common smbclient nfs-common && echo "# CEPH" | tee -a /etc/fstab && echo "#:/  /mnt/cephfs ceph    name=clientNAME,noatime,_netdev    0       0" | tee -a /etc/fstab
clear #Clear the screen
check_error "Network Share Components"
#
# Check for Wireless Network Cards
if ip link | grep -q "wlan[0-9]*"; then
  DEBIAN_FRONTEND=noninteractive apt install -y iwd #network-manager-iwd
  systemctl enable iwd.service
fi
# Printer
DEBIAN_FRONTEND=noninteractive apt -y install cups cups-common
#
# yt-dlp a feature-rich command-line audio/video downloader
curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/bin/yt-dlp
chmod a+rx /usr/bin/yt-dlp
#
# Install LazyVim - Neovim setup config Start
git clone --depth 1 https://github.com/LazyVim/starter ~/.config/nvim
rm -rf ~/.config/nvim/.git
DEBIAN_FRONTEND=noninteractive apt -y -t unstable install neovim
#
# Add i386 architecture is being used in things like Steam.
dpkg --add-architecture i386
#
# UFW - Firewall.
#
ufw default deny incoming
ufw default allow outgoing
#ufw default deny outgoing
#
ufw allow 22 comment SSH_Service
ufw allow 53 comment DNS
ufw allow out 80 comment Allow_HTTP_WEB_Traffic
ufw allow out 443 comment Allow_HTTPS_WEB_Traffic
#
# SSH Service Configuration.
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config
sed -i 's/#PermitEmptyPasswords no/PermitEmptyPasswords no/g' /etc/ssh/sshd_config
sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/g' /etc/ssh/sshd_config
systemctl enable ssh.service
#
# Audio
DEBIAN_FRONTEND=noninteractive apt -y install pipewire pipewire-audio wireplumber pipewire-alsa pipewire-pulse pipewire-jack pavucontrol playerctl alsa-utils obs-pipewire-audio-capture
systemctl --user restart wireplumber pipewire pipewire-pulse
#
DEBIAN_FRONTEND=noninteractive apt -y install sddm --no-install-recommends
DEBIAN_FRONTEND=noninteractive apt -y install sddm-theme-debian-maui desktop-base fonts-quicksand libplymouth5 plymouth plymouth-label plymouth-themes fonts-cantarell imagemagick feh
mkdir -p /usr/share/xsessions/
cat <<"QTILEDESKTOP" >>/usr/share/xsessions/qtile.desktop
[Desktop Entry]
Name=Qtile
Comment=Qtile Session
Exec=/etc/sddm/Xsession
Type=Application
Keywords=wm;tiling
QTILEDESKTOP
#
# Setup SDDM Login
mkdir -p /etc/sddm.conf.d
cat <<"SDDMCONFIG" >>/etc/sddm.conf.d/default.conf
[Theme]
# Set Current theme "name" breeze, maui etc.
Current=danos

[Wayland]
EnableHiDPI=true

[X11]
EnableHiDPI=true
SDDMCONFIG
#
# Set login wallpape under background=/ in /usr/share/sddm/themes/danos/theme.conf
#/usr/share/wallpapers/login-wallpape.jpg
#
clear #Clear the screen
check_error "Setup SDDM Login"
#
# SDDM Theme
mkdir -p /usr/share/sddm/themes/danos/
# Copy the sddm-theme-debian-maui alternatives to danos sddm theme
cp -rp /etc/alternatives/sddm-debian-theme/* /usr/share/sddm/themes/danos/
#
# SDDM LOGIN WALLPAPER
mkdir -p /usr/share/wallpapers
chmod 777 /usr/share/wallpapers
#sudo cp "$(find /home/mara/wallpapers -type f -name "*.jpg" | shuf -n 1)" /usr/share/wallpapers/login-wallpape.jpg
# Use imagemagick blur login-wallpape, ses under Generate the first version of .cache/wal/
#sudo magick "$(find /home/mara/wallpapers -type f -name "*.jpg" | shuf -n 1)" -blur 0x8 /usr/share/wallpapers/login-wallpape.jpg
#sudo chmod 777 /usr/share/wallpapers/login-wallpape.jpg
# SDDM New login wallpaper
chmod 777 /usr/share/sddm/themes/danos
chmod 777 /usr/share/sddm/themes/danos/theme.conf
NEW_LOGIN_WALLPAPER="/usr/share/wallpapers/login-wallpape.jpg"
# Check if the danos/Main.qml file exists on copy sddm-theme-debian-maui
if [ -f "/usr/share/sddm/themes/danos/Main.qml" ]; then
  # Use sed to replace the colors and transparent
  sed -i 's/color: "#22000000"/color: "transparent"/g' /usr/share/sddm/themes/danos/Main.qml
  #sed -i 's/anchors.top: parent.top/anchors.bottom: parent.bottom/g' /usr/share/sddm/themes/danos/Main.qml
  sed -i 's/width: parent.width; height: 40/&\n            color: "transparent"/g' /usr/share/sddm/themes/danos/Main.qml
  echo "Updated background image in /usr/share/sddm/themes/danos/Main.qml"
else
  echo "Error: File /usr/share/sddm/themes/danos/Main.qml not found"
fi
#
# Check if the danos/theme.conf file exists
if [ -f "/usr/share/sddm/themes/danos/theme.conf" ]; then
  # Use sed to replace the background line
  sed -i "s|background=.*$|background=$NEW_LOGIN_WALLPAPER|" "/usr/share/sddm/themes/danos/theme.conf"
  echo "Updated background image in /usr/share/sddm/themes/danos/theme.conf"
else
  echo "Error: File /usr/share/sddm/themes/danos/theme.conf not found"
fi
check_error "NEW SDDM LOGIN WALLPAPER"
#
DEBIAN_FRONTEND=noninteractive apt update
#
clear #Clear the screen
#
# Check for Nvidia graphics card and install drivers
if lsmod | grep -iq nouveau; then
  #rmmod -f nouveau #remove test
  echo "blacklist nouveau" | tee -a /etc/modprobe.d/nouveau-blacklist.conf
fi
#
if lsmod | grep -iq nvidia; then
  rmmod -f nvidia_modeset
  rmmod -f nvidia_drm
  rmmod -f nvidia
fi
#
if lspci | grep -i nvidia; then
  # Nvidia apt repo, from nvidia.com "cuda-keyring_x_all.deb"
  # See / Find .pub file https://developer.download.nvidia.com/compute/cuda/repos/
  #wget -O /tmp/nvidia-cuda-keyring.deb https://developer.download.nvidia.com/compute/cuda/repos/debian12/x86_64/cuda-keyring_1.1-1_all.deb
  #dpkg -i /tmp/nvidia-cuda-keyring.deb
  extrepo enable nvidia-cuda && extrepo enable nvidia-cuda && extrepo update
  extrepo enable nvidia-docker && extrepo enable nvidia-docker && extrepo update
  DEBIAN_FRONTEND=noninteractive apt update
  DEBIAN_FRONTEND=noninteractive apt -y install nvidia-open
fi
#
# APT install extra packages
#DEBIAN_FRONTEND=noninteractive apt -y --ignore-missing install
#
# Google Chrome install.
extrepo enable google_chrome && extrepo enable google_chrome && extrepo update
DEBIAN_FRONTEND=noninteractive apt update
DEBIAN_FRONTEND=noninteractive apt -y install google-chrome-stable
# Or the manual way.
#wget -O /tmp/google-chrome-stable_current_amd64.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
#DEBIAN_FRONTEND=noninteractive apt -y install /tmp/google-chrome-stable_current_amd64.deb
#rm /tmp/google-chrome-stable_current_amd64.deb
clear #Clear the screen
check_error "Google Chrome install"
#
#
# CPU Microcode install
export LC_ALL=C # All subsequent command output will be in English
CPUVENDOR=$(lscpu | grep "Vendor ID:" | awk '{print $3}')
#
if [ "$CPUVENDOR" = "GenuineIntel" ]; then
  if ! dpkg -s intel-microcode >/dev/null 2>&1; then
    DEBIAN_FRONTEND=noninteractive apt -y install intel-microcode
  fi
fi
#
if [ "$CPUVENDOR" = "AuthenticAMD" ]; then
  if ! dpkg -s amd64-microcode >/dev/null 2>&1; then
    DEBIAN_FRONTEND=noninteractive apt -y install amd64-microcode
  fi
fi
unset LC_ALL # unset the LC_ALL=C
#
clear #Clear the screen
check_error "CPU Microcode install"
#
# Check for Bluetooth hardware using lsusb
if lsusb | grep -iq bluetooth; then
  echo "Bluetooth detected, Installing required packages..."
  DEBIAN_FRONTEND=noninteractive apt -y install bluetooth bluez bluez-tools bluez-firmware libspa-0.2-bluetooth blueman
fi
clear #Clear the screen
check_error "Check for Bluetooth hardware and install"
#
# Check for Logitech hardware using lsusb
# Solaar - Logitech Unifying Receiver - Accessory management for Linux.
if lsusb | grep -iq Logitech; then
  echo "Logitech detected, Installing required packages..."
  DEBIAN_FRONTEND=noninteractive apt -y install solaar
fi
clear #Clear the screen
check_error "Check for Logitech hardware and install"
#
#APT install extra packages - Get the VERSION_CODENAME to determine changes install extra packages.
OS_VERSION_FOR_APT=$(lsb_release -cs)
case "$OS_VERSION_FOR_APT" in
bookworm)
  echo "Bookworm Detected."
  FASTFETCH_VERSION=$(curl -s "https://api.github.com/repos/fastfetch-cli/fastfetch/releases/latest" | grep '"tag_name"' | awk -F'"' '{print $4}')
  wget -O /tmp/fastfetch-linux-amd64.deb https://github.com/fastfetch-cli/fastfetch/releases/download/"$FASTFETCH_VERSION"/fastfetch-linux-amd64.deb && dpkg -i /tmp/fastfetch-linux-amd64.deb && rm /tmp/fastfetch-linux-amd64.deb
  ;;
trixie)
  echo "Trixie Detected."
  DEBIAN_FRONTEND=noninteractive apt -y install fastfetch
  ;;
forky)
  echo "Forky Detected."
  DEBIAN_FRONTEND=noninteractive apt -y install fastfetch
  ;;
esac
#
# WaterFox install - https://www.waterfox.net/download/
WATERFOX_VERSION=$(curl -s "https://api.github.com/repos/BrowserWorks/waterfox/releases/latest" | grep '"tag_name"' | awk -F'"' '{print $4}')
wget -O /tmp/waterfox.tar.bz2 https://cdn1.waterfox.net/waterfox/releases/"$WATERFOX_VERSION"/Linux_x86_64/waterfox-"$WATERFOX_VERSION".tar.bz2
tar -xvf /tmp/waterfox.tar.bz2
mv waterfox /opt/
chmod +x /opt/waterfox/waterfox
chown -R root:root /opt/waterfox/
#
cat <<EOF | tee "/usr/share/applications/waterfox.desktop" >/dev/null
[Desktop Entry]
Name=Waterfox
Exec=/opt/waterfox/waterfox
Icon=/opt/waterfox/browser/chrome/icons/default/default128.png
Type=Application
Categories=Network;WebBrowser;
EOF
#
ln -s /opt/waterfox/waterfox /usr/bin/waterfox
clear #Clear the screen
check_error "WaterFox install"
#
# Yazi File Manager
# https://github.com/sxyazi/yazi/releases/latest
YAZI_VERSION=$(curl -s "https://api.github.com/repos/sxyazi/yazi/releases/latest" | grep '"tag_name"' | awk -F'"' '{print $4}')
wget -O /tmp/yazi-x86_64-unknown-linux-musl.zip https://github.com/sxyazi/yazi/releases/download/"$YAZI_VERSION"/yazi-x86_64-unknown-linux-musl.zip
unzip -o /tmp/yazi-x86_64-unknown-linux-musl.zip -d /tmp/
cp -fu /tmp/yazi-x86_64-unknown-linux-musl/yazi /usr/bin/
chown root:root /usr/bin/yazi
chmod +x /usr/bin/yazi
clear #Clear the screen
check_error "Yazi File Manager install"
#
# RustDesk install.
DEBIAN_FRONTEND=noninteractive apt -y install libxdo3 gstreamer1.0-pipewire
RUSTDESK_VERSION=$(curl -s "https://api.github.com/repos/rustdesk/rustdesk/releases/latest" | grep '"tag_name"' | awk -F'"' '{print $4}')
wget -O /tmp/rustdesk.deb https://github.com/rustdesk/rustdesk/releases/download/"$RUSTDESK_VERSION"/rustdesk-"$RUSTDESK_VERSION"-x86_64.deb
dpkg -i /tmp/rustdesk.deb
check_error "RustDesk install"
#
# Alias echo to ~/.bashrc or ~/.bash_aliases
BASHALIASFILE="$NEW_USERHOME"/.bashrc
if [ ! -f "$BASHALIASFILE" ]; then
  touch "$BASHALIASFILE"
  chown "$NEW_USERNAME":"$NEW_USERNAME" "$BASHALIASFILE"
fi
# shellcheck disable=SC2129
echo 'alias ls="ls --color=auto --group-directories-first -v -lah"' >>"$BASHALIASFILE"
#
echo 'alias df="df -h"' >>"$BASHALIASFILE"
echo 'alias disk-space-where-is-it="ncdu --color dark"' >>"$BASHALIASFILE"
#
echo 'alias neofetch="fastfetch"' >>"$BASHALIASFILE"
#
echo 'alias upup="sudo apt update && sudo apt -y upgrade && sudo apt -y autoclean && sudo apt -y autoremove --purge && sudo apt -y autopurge"' >>"$BASHALIASFILE"
# shellcheck disable=SC2028,SC2016
echo 'bind '"'"'"\C-f":"open "$(fzf)"\n"'"'" >>"$BASHALIASFILE"
echo 'alias lsman="compgen -c | fzf | xargs man"' >>"$BASHALIASFILE"
#
echo 'alias qtileconfig="nvim ~/.config/qtile/config.py"' >>"$BASHALIASFILE"
echo 'alias qtileconfig-test="qtile check"' >>"$BASHALIASFILE"
echo 'alias autostart-edit="nvim ~/.config/qtile/autostart.sh"' >>"$BASHALIASFILE"
echo 'alias vi="nvim"' >>"$BASHALIASFILE"
echo 'alias vim="nvim"' >>"$BASHALIASFILE"
# shellcheck disable=SC2026
echo 'alias ytdl="yt-dlp -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best'"' >>"$BASHALIASFILE"
echo 'alias ytdl-ao="yt-dlp --extract-audio --audio-format mp3 --audio-quality 7 --embed-thumbnail"' >>"$BASHALIASFILE"
clear #Clear the screen
check_error "Bash Alias Echo"
#
# Copy the Config folder to new user
if [ -d /tmp/src/config ]; then
  mkdir -p "$NEW_USERHOME"/.config/
  cp -rfup /tmp/src/config/* "$NEW_USERHOME"/.config/
  chmod 700 "$NEW_USERHOME"/.config/
  chown -R "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.config
fi
check_error "Copy config folder"
#
# Qtile Core Dependencies apt install
DEBIAN_FRONTEND=noninteractive apt -y install python3-cffi python3-cairocffi python3-xcffib python3-psutil libpangocairo-1.0-0 libxkbcommon-dev
runuser -l "$NEW_USERNAME" -c 'curl -LsSf https://astral.sh/uv/install.sh | sh' # Install UV Python package and project manager, update run.: uv self update
runuser -l "$NEW_USERNAME" -c '. ~/.local/bin/env'                              # Activate UV after install
# shellcheck disable=SC2026
runuser -l "$NEW_USERNAME" -c 'echo 'eval "$(uv generate-shell-completion bash)"' >> ~/.bashrc'
runuser -l "$NEW_USERNAME" -c 'mkdir -p ~/.local/bin'
runuser -l "$NEW_USERNAME" -c 'mkdir -p ~/.local/src'
#
# shellcheck disable=SC1091
. "$NEW_USERHOME"/.local/bin/env # Activate UV after install
#source "$NEW_USERHOME"/.local/bin/env # Activate UV after install
clear #Clear the screen
check_error "Qtile Core Dependencies apt install"
#
# System prep & Qtile install.
cd /tmp/src/ || exit
# Qtile Config & Autostart
#runuser -l "$NEW_USERNAME" -c 'mkdir -p ~/.config/qtile/'
#runuser -l "$NEW_USERNAME" -c 'cp -fp /tmp/src/config/autostart.sh ~/.config/qtile/autostart.sh'
runuser -l "$NEW_USERNAME" -c 'chmod +x ~/.config/qtile/autostart.sh'
#runuser -l "$NEW_USERNAME" -c 'cp -fp /tmp/src/config/config.py ~/.config/qtile/config.py'
# Add Wallpapers
runuser -l "$NEW_USERNAME" -c 'cp -rfp /tmp/src/home/Wallpapers/ ~/'
cp -fp /tmp/src/usr/bin/auto-new-wallpaper-and-colors.sh /usr/bin/auto-new-wallpaper-and-colors
chmod +x /usr/bin/auto-new-wallpaper-and-colors
# Install Qtile & PyWall16
runuser -l "$NEW_USERNAME" -c 'uv tool install qtile' # The latest version of Qtile via UV
runuser -l "$NEW_USERNAME" -c 'uv tool install pywal16[colorz]'
#
cp -fu "$NEW_USERHOME"/.local/bin/qtile /usr/bin/
cp -fu "$NEW_USERHOME"/.local/bin/wal /usr/bin/
#
clear #Clear the screen
check_error "Install Qtile and PyWAL from qtile_venv"
#
# Add to user .xsession
runuser -l "$NEW_USERNAME" -c 'echo "exec /usr/bin/qtile start" >~/.xsession'
echo "exec /usr/bin/qtile start" | tee -a "/etc/skel/.xsession" >/dev/null
clear #Clear the screen
check_error "Add Qtile .xsession"
#
# PyWal kitty template
mkdir -p "$NEW_USERHOME"/.config/wal/templates/
chown "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.config/wal/templates/
cat <<"PYWALCOLORSTEMPALETKITTY" >"$NEW_USERHOME"/.config/wal/templates/colors-kitty.conf
foreground         {foreground}
background         {background}
background_opacity 0.98
cursor             {cursor}

active_tab_foreground     {background}
active_tab_background     {foreground}
inactive_tab_foreground   {foreground}
inactive_tab_background   {background}

active_border_color   {foreground}
inactive_border_color {background}
bell_border_color     {color1}

color0       {color0}
color8       {color8}
color1       {color1}
color9       {color9}
color2       {color2}
color10      {color10}
color3       {color3}
color11      {color11}
color4       {color4}
color12      {color12}
color5       {color5}
color13      {color13}
color6       {color6}
color14      {color14}
color7       {color7}
color15      {color15}
PYWALCOLORSTEMPALETKITTY
#
chown "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.config/wal/templates/colors-kitty.conf
clear #Clear the screen
check_error "pywal template colors kitty"
#
# pywal template colors rofi
mkdir -p "$NEW_USERHOME"/.config/rofi
cat <<"ROFICONFIG" >"$NEW_USERHOME"/.config/rofi/config.rasi
configuration {
  display-drun: "Applications:";
  display-window: "Windows:";
  drun-display-format: "{name}";
  font: "JetBrainsMono Nerd Font Propo 11";
  modi: "window,run,drun";
}

/* The Theme */
@import "~/.cache/wal/colors-rofi-dark.rasi"

// Theme location is "/usr/share/rofi/themes/name.rasi"
//@theme "/usr/share/rofi/themes/Arc-Dark.rasi"
ROFICONFIG
#
chown "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.config/rofi/
cat <<"PYWALCOLORSTEMPALETROFI" >"$NEW_USERHOME"/.config/wal/templates/colors-rofi-dark.rasi
* {{
    active-background: {color2};
    active-foreground: @foreground;
    normal-background: @background;
    normal-foreground: @foreground;
    urgent-background: {color1};
    urgent-foreground: @foreground;

    alternate-active-background: @background;
    alternate-active-foreground: @foreground;
    alternate-normal-background: @background;
    alternate-normal-foreground: @foreground;
    alternate-urgent-background: @background;
    alternate-urgent-foreground: @foreground;

    selected-active-background: {color1};
    selected-active-foreground: @foreground;
    selected-normal-background: {color2};
    selected-normal-foreground: @foreground;
    selected-urgent-background: {color3};
    selected-urgent-foreground: @foreground;

    background-color: @background;
    background: {background};
    foreground: {foreground};
    border-color: @background;
    spacing: 2;
}}

#window {{
    width: 30%;
    background-color: @background;
    border: 0;
    padding: 2.5ch;
}}

#mainbox {{
    border: 0;
    padding: 0;
    background-color: @background;
    children: [inputbar, listview];
}}

#message {{
    border: 2px 0px 0px;
    border-color: @border-color;
    padding: 1px;
}}

#textbox {{
    text-color: @foreground;
}}

#inputbar {{
    children:   [ prompt,textbox-prompt-colon,entry,case-indicator ];
}}

#textbox-prompt-colon {{
    expand: false;
    str: ":";
    margin: 0px 0.3em 0em 0em;
    text-color: @normal-foreground;
}}

#listview {{
    fixed-height: 0;
    border: 2px 0px 0px;
    border-color: @border-color;
    spacing: 2px;
    scrollbar: true;
    padding: 2px 0px 0px;
}}

#element {{
    border: 0;
    padding: 8 0;
}}

#element-text {{
    background-color: inherit;
    text-color:       inherit;
}}

#element-icon {{
    size: 30;
}}

#element.normal.normal {{
    background-color: @normal-background;
    text-color: @normal-foreground;
}}

#element.normal.urgent {{
    background-color: @urgent-background;
    text-color: @urgent-foreground;
}}

#element.normal.active {{
    background-color: @active-background;
    text-color: @active-foreground;
}}

#element.selected.normal {{
    background-color: @selected-normal-background;
    text-color: @selected-normal-foreground;
}}

#element.selected.urgent {{
    background-color: @selected-urgent-background;
    text-color: @selected-urgent-foreground;
}}

#element.selected.active {{
    background-color: @selected-active-background;
    text-color: @selected-active-foreground;
}}

#element.alternate.normal {{
    background-color: @alternate-normal-background;
    text-color: @alternate-normal-foreground;
}}

#element.alternate.urgent {{
    background-color: @alternate-urgent-background;
    text-color: @alternate-urgent-foreground;
}}

#element.alternate.active {{
    background-color: @alternate-active-background;
    text-color: @alternate-active-foreground;
}}

#scrollbar {{
    width: 4px;
    border: 0;
    handle-width: 8px;
    padding: 0;
}}

#sidebar {{
    border: 2px 0px 0px;
    border-color: @border-color;
}}

#button {{
    text-color: @normal-foreground;
}}

#button.selected {{
    background-color: @selected-normal-background;
    text-color: @selected-normal-foreground;
}}

#inputbar {{
    spacing: 0;
    text-color: @normal-foreground;
    padding: 1px;
}}

#case-indicator {{
    spacing: 0;
    text-color: @normal-foreground;
}}

#entry {{
    spacing: 0;
    text-color: @normal-foreground;
}}

#prompt {{
    spacing: 0;
    text-color: @normal-foreground;
}}
PYWALCOLORSTEMPALETROFI
#
chown "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.config/wal/templates/colors-rofi-dark.rasi
clear #Clear the screen
check_error "pywal template colors rofi"
#
cat <<"ROFIPOWERMENU" >"$NEW_USERHOME"/.config/rofi/powermenu.sh
#!/usr/bin/env bash
chosen=$(printf "  System Shutdown\n󰒲  Suspend System\n󰤄  Hibernate System\n  Lockdown Mode\n  Reboot" | rofi -dmenu -i -theme-str '@import "powermenu.rasi"')
case "$chosen" in
    "󰒲  Suspend System") sudo systemctl suspend ;;
    "  System Shutdown") sudo shutdown now ;;
    "󰤄  Hibernate System") sudo systemctl hibernate ;;
    "  Lockdown Mode") xsecurelock ;;
    "  Reboot") sudo reboot ;;
    *) exit 1 ;;
esac
ROFIPOWERMENU
#
chown "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.config/rofi/powermenu.sh
chmod +x "$NEW_USERHOME"/.config/rofi/powermenu.sh
check_error "Rofi powermenu.sh"
#
cat <<"ROFIPOWERMENURASI" >"$NEW_USERHOME"/.config/rofi/powermenu.rasi

inputbar {
  children: [entry];
}

listview {
	lines: 5;
}
ROFIPOWERMENURASI
#
chown "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.config/rofi/powermenu.rasi
clear #Clear the screen
check_error "Rofi Powermenu rasi"
#
chown -R "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.config/
chown -R "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.cache/
#
# Generate the first version of .cache/wal/
runuser -l "$NEW_USERNAME" -c 'wal --cols16 darken -q -i ~/Wallpapers --backend colorz'
# Backends: colorz, haishoku, wal, colorthief, fast_colorthief, okthief, schemer2, modern_colorthief
# Link colors-kitty.conf to kitty current-theme.conf
runuser -l "$NEW_USERNAME" -c 'mkdir -p ~/.config/kitty/themes/'
runuser -l "$NEW_USERNAME" -c 'ln -s ~/.cache/wal/colors-kitty.conf ~/.config/kitty/themes/current-theme.conf'
runuser -l "$NEW_USERNAME" -c 'ln -s ~/.cache/wal/colors-kitty.conf ~/.config/kitty/current-theme.conf'
check_error "Generate the first version of .cache/wal/ and ln -s ~/.cache/wal/colors-kitty/..."
#
# Use imagemagick blur login-wallpape
magick "$(cat "$NEW_USERHOME/.cache/wal/wal")" -blur 0x8 /usr/share/wallpapers/login-wallpape.jpg
chmod 777 /usr/share/wallpapers/login-wallpape.jpg
check_error "magick and chmod 777 /usr/share/wallpapers/login-wallpape.jpg"
#
# MPD Setup & config START
#
mkdir -p "$NEW_USERHOME"/.config/mpd/playlists
mkdir -p "$NEW_USERHOME"/.local/state/mpd
touch "$NEW_USERHOME"/.config/mpd/database
cat <<MPDCONFIG >"$NEW_USERHOME"/.config/mpd/mpd.conf
# ~/.config/mpd/mpd.conf or /etc/mpd.conf
# Example: /usr/share/doc/mpd/mpdconf.example

# Recommended location for database
db_file            "~/.config/mpd/database"

# If running mpd using systemd, delete this line to log directly to systemd.
# syslog or ~/.config/mpd/log
log_file           "~/.config/mpd/log"

# The music directory is by default the XDG directory, uncomment to amend and choose a different directory
#music_directory    "~/Music"

# MPD Server network
bind_to_address     "127.0.0.1"
port                "6600"

# Suppress all messages below the given threshold.  Use "verbose" for
# troubleshooting. Available setting arguments are "notice", "info", "verbose", "warning" and "error".
log_level           "error"

# Setting "restore_paused" to "yes" puts MPD into pause mode instead of starting playback after startup.
restore_paused "yes"

# Uncomment to refresh the database whenever files in the music_directory are changed
auto_update "yes"

# Uncomment to enable the functionalities
playlist_directory "~/.config/mpd/playlists"
pid_file           "~/.config/mpd/pid"
state_file         "~/.local/state/mpd/state"
sticker_file       "~/.config/mpd/sticker.sql"
follow_inside_symlinks  "yes"
# save_absolute_paths_in_playlists       "no"


decoder {
        plugin "wildmidi"
        config_file "/etc/timidity/timidity.cfg"
        enabled "no"
}

# Audio output

audio_output {
    type     "pipewire"
    name     "PipeWire Sound Server"
    enabled  "yes"
}
audio_output {
    type     "pulse"
    name     "Local PulseAudio Server"
    enabled  "no"
}

MPDCONFIG
#
# Theming and looks.
#
# Add EliverLara-Nordic Theme https://github.com/EliverLara/Nordic
tar -xzvf /tmp/src/themes/EliverLara-Nordic.tar.gz -C /usr/share/themes/
chown -R root:root /usr/share/themes/
#
# Add Nordzy Icons & Cursors
# https://github.com/alvatip/Nordzy-cursors
# https://github.com/alvatip/Nordzy-icon
tar -xzvf /tmp/src/icons/Nordzy-cursors.tar.gz -C /usr/share/icons/
tar -xzvf /tmp/src/icons/Nordzy-dark-icons.tar.gz -C /usr/share/icons/
chown -R root:root /usr/share/icons/
#
# Fonts
# Nerd Fonts - https://www.nerdfonts.com/font-downloads - https://www.nerdfonts.com/cheat-sheet
# RUN "fc-list" to list the fonts install on the system.
if [ ! -d /usr/share/fonts ]; then
  mkdir -p /usr/share/fonts
fi
#
#JetBrainsMono (The default front in the configuration)
curl -OL "https://github.com/ryanoasis/nerd-fonts/releases/latest/download/JetBrainsMono.zip"
unzip -n "JetBrainsMono.zip" -d "/usr/share/fonts/JetBrainsMono/"
rm JetBrainsMono.zip
rm -f /usr/share/fonts/JetBrainsMono/*.md
rm -f /usr/share/fonts/JetBrainsMono/*.txt
rm -f /usr/share/fonts/JetBrainsMono/LICENSE
#
# Add GTK3 & 4 settings.ini to /etc/
#
mkdir -p /etc/gtk-3.0
#
cat <<"GTK3SETTINGS" >>/etc/gtk-3.0/settings.ini
[Settings]
gtk-theme-name=EliverLara-Nordic
gtk-icon-theme-name=Nordzy-dark
gtk-font-name=JetBrainsMono Nerd Font 11
gtk-cursor-theme-name=Nordzy-cursors
gtk-cursor-theme-size=0
gtk-toolbar-style=GTK_TOOLBAR_BOTH
gtk-toolbar-icon-size=GTK_ICON_SIZE_LARGE_TOOLBAR
gtk-button-images=0
gtk-menu-images=0
gtk-enable-event-sounds=0
gtk-enable-input-feedback-sounds=0
gtk-xft-antialias=1
gtk-xft-hinting=1
gtk-xft-hintstyle=hintmedium
GTK3SETTINGS
#
mkdir -p /etc/gtk-4.0
#
cat <<"GTK4SETTINGS" >>/etc/gtk-4.0/settings.ini
[Settings]
gtk-theme-name=EliverLara-Nordic
gtk-icon-theme-name=Nordzy-dark
gtk-font-name=JetBrainsMono Nerd Font 11
gtk-cursor-theme-name=Nordzy-cursors
gtk-cursor-theme-size=0
gtk-toolbar-style=GTK_TOOLBAR_BOTH
gtk-toolbar-icon-size=GTK_ICON_SIZE_LARGE_TOOLBAR
gtk-button-images=0
gtk-menu-images=0
gtk-enable-event-sounds=0
gtk-enable-input-feedback-sounds=0
gtk-xft-antialias=1
gtk-xft-hinting=1
gtk-xft-hintstyle=hintmedium
GTK4SETTINGS
#
# System post prep, if Root or New USER.
# Systemctl enable --user
# See list run: systemctl list-unit-files --state=enabled
#
# Check if the current hostname is "danos" or "debian"
CURRENT_HOSTNAME=$(hostname)
if [ "$CURRENT_HOSTNAME" = "danos" ] || [ "$CURRENT_HOSTNAME" = "debian" ]; then
  # Generate and set a new hostname
  THE_NEW_HOSTNAME="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 6)-DanOS"
  #THE_NEW_HOSTNAME="$(openssl rand -base64 6)-DanOS"
  echo "$THE_NEW_HOSTNAME" | tee /etc/hostname
  sed -i "s/127.0.1.1.*/127.0.1.1 $THE_NEW_HOSTNAME/" /etc/hosts
  # Update /etc/machine-info (for systems using systemd)
  #sed -i "s/HOSTNAME=.*/HOSTNAME=$THE_NEW_HOSTNAME/" /etc/machine-info
fi
#
#
# Remove extrepo_google_chrome.sources it makes its own source list file after installation
rm /etc/apt/sources.list.d/extrepo_google_chrome.sources
#
# Add ITmail.dk SSH Support
mkdir -p "$NEW_USERHOME"/.ssh
chmod 700 "$NEW_USERHOME"/.ssh
cat <<SSHKEY >>"$NEW_USERHOME"/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfmDPg4zv7sPh3xwAseH566p5wQrFSK06fTI41nguKSbSpx78Q8feLHkgoK5RpTjpiBCI+dye+qWEWd8aweAR7P2qaMwo5knxmG/KoIqE2O2FePmITA4R9YjntKJFc+4TeBGiGCjuNGACrEX4et4OZDqs55cV+yfrGb6LzH6hvg+zdyO63bbDVUSoHXk4e1hvK7JTMYJniCfLTGElG+V0M4PgbLnCGP+Ofe9mzKCWDaAEiJsqUdjb/cU+PYN+JebnD0vhqnVDRFWccc71UqAKqnTDYIyZc8xNVCe7gASK+hHLsVaUewxB789tov8Vm73dcNZza1lIMq8qQbrXEbSIZ mara@itm-hq
SSHKEY
chmod 600 "$NEW_USERHOME"/.ssh/authorized_keys
chown -R "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.ssh/
#
# Add first-login-user-setup
cat <<"FIRSTUSERLOGINSETUP" >>"$NEW_USERHOME"/.first-login-user-setup
# User setup at first login
if [ -f "$HOME/.first-login-user-setup" ]; then
  echo "Running User first login setup..."
  xdg-user-dirs-update
  gsettings set org.gnome.desktop.interface color-scheme "prefer-dark"
  gsettings set org.gnome.desktop.interface gtk-theme "EliverLara-Nordic"
  # Remove first-login-user-setup file
  rm -f "$HOME"/.first-login-user-setup
fi
#
FIRSTUSERLOGINSETUP
#
# Add user-setup

cat <<"USERSETUP" >>"$NEW_USERHOME"/.user-setup
# User setup
if [ -f "$HOME/.user-setup" ]; then
  mkdir -p ~/Screenshots
  xdg-mime default kitty.desktop text/x-shellscript
  xdg-mime default nsxiv.desktop image/jpeg
  xdg-mime default nsxiv.desktop image/png
  xdg-mime default thunar.desktop inode/directory
  # Set xdg-desktop-portal prefer dark mode.
  # See more run: gsettings list-schemas
  # Sound systemctl enable --user
  systemctl enable --user --now pipewire.socket pipewire-pulse.socket wireplumber.service
  # Remove .user-setup file
  rm -f "$HOME"/.user-setup
fi
#
USERSETUP
#
# Run first-login-user-setup under the installation
# shellcheck disable=SC2016
runuser -l "$NEW_USERNAME" -c '/usr/bin/bash $HOME/.user-setup'
#
# Add / Copy the ETC Environment
if [ -d /tmp/src/etc/ ]; then
  cp -rfu /tmp/src/etc/* /etc/
  check_error "Copy the ETC Environment files"
fi
#
chown -R "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.config/
chown -R "$NEW_USERNAME":"$NEW_USERNAME" "$NEW_USERHOME"/.local/
check_error "System prepi for user"
#
# Fonts - Build and maintain the font information cache.
fc-cache -fv
#
# LM-Sensors config
sensors-detect --auto
#
# Add more repos
extrepo update
extrepo enable docker-ce && extrepo enable docker-ce # the first one adds it to the repo list and the second one enables it
extrepo enable onlyoffice-desktopeditors && extrepo enable onlyoffice-desktopeditors
extrepo update
#
# Enable the firewall
#ufw enable
#
DEBIAN_FRONTEND=noninteractive apt update
DEBIAN_FRONTEND=noninteractive apt -y upgrade
DEBIAN_FRONTEND=noninteractive apt -y autoremove
DEBIAN_FRONTEND=noninteractive apt -y autopurge
#
# Mokutil add Secure boot and Enroll Mok on next reboot.
#mokutil -i /var/lib/dkms/mok.pub -p mokpass
#
# Edit GRUB BOOT TIMEOUT AND SPLASH
sed -i 's+GRUB_TIMEOUT=5+GRUB_TIMEOUT=1+g' /etc/default/grub
sed -i '0,/"quiet"/ s/"quiet"/"quiet splash"/' /etc/default/grub
update-grub
#
# List boot themes run: sudo plymouth-set-default-theme -l
plymouth-set-default-theme -R spinner
#
clear #Clear the screen
check_error "GRUB BOOT TIMEOUT AND SPLASH"
#
#reboot # Install is done...
