#!/usr/bin/env bash
clear

printf "\n%.0s" {1..2}  
echo -e "\e[35m
 ███▄    █  ██▓▒██   ██▒ ▒█████    ██████  ▄████▄   ▒█████   ███▄    █   █████▒██▓  ▄████ 
 ██ ▀█   █ ▓██▒▒▒ █ █ ▒░▒██▒  ██▒▒██    ▒ ▒██▀ ▀█  ▒██▒  ██▒ ██ ▀█   █ ▓██   ▒▓██▒ ██▒ ▀█▒
▓██  ▀█ ██▒▒██▒░░  █   ░▒██░  ██▒░ ▓██▄   ▒▓█    ▄ ▒██░  ██▒▓██  ▀█ ██▒▒████ ░▒██▒▒██░▄▄▄░
▓██▒  ▐▌██▒░██░ ░ █ █ ▒ ▒██   ██░  ▒   ██▒▒▓▓▄ ▄██▒▒██   ██░▓██▒  ▐▌██▒░▓█▒  ░░██░░▓█  ██▓
▒██░   ▓██░░██░▒██▒ ▒██▒░ ████▓▒░▒██████▒▒▒ ▓███▀ ░░ ████▓▒░▒██░   ▓██░░▒█░   ░██░░▒▓███▀▒
░ ▒░   ▒ ▒ ░▓  ▒▒ ░ ░▓ ░░ ▒░▒░▒░ ▒ ▒▓▒ ▒ ░░ ░▒ ▒  ░░ ▒░▒░▒░ ░ ▒░   ▒ ▒  ▒ ░   ░▓   ░▒   ▒ 
░ ░░   ░ ▒░ ▒ ░░░   ░▒ ░  ░ ▒ ▒░ ░ ░▒  ░ ░  ░  ▒     ░ ▒ ▒░ ░ ░░   ░ ▒░ ░      ▒ ░  ░   ░ 
   ░   ░ ░  ▒ ░ ░    ░  ░ ░ ░ ▒  ░  ░  ░  ░        ░ ░ ░ ▒     ░   ░ ░  ░ ░    ▒ ░░ ░   ░ 
         ░  ░   ░    ░      ░ ░        ░  ░ ░          ░ ░           ░         ░        ░ 
                                          ░                                               
\e[0m"
printf "\n%.0s" {1..1}

OK="$(tput setaf 2)[OK]$(tput sgr0)"
ERROR="$(tput setaf 1)[ERROR]$(tput sgr0)"
NOTE="$(tput setaf 3)[NOTE]$(tput sgr0)"
INFO="$(tput setaf 4)[INFO]$(tput sgr0)"
WARN="$(tput setaf 1)[WARN]$(tput sgr0)"
CAT="$(tput setaf 6)[ACTION]$(tput sgr0)"
MAGENTA="$(tput setaf 5)"
ORANGE="$(tput setaf 214)"
WARNING="$(tput setaf 1)"
YELLOW="$(tput setaf 3)"
GREEN="$(tput setaf 2)"
BLUE="$(tput setaf 4)"
SKY_BLUE="$(tput setaf 6)"
RESET="$(tput sgr0)"

set -e

if [ -n "$(grep -i nixos < /etc/os-release)" ]; then
  echo "${OK} verified distro to be nixos"
else
  echo "$ERROR this is not nixos or the distro info is not available!"
  exit 1
fi

if command -v git &> /dev/null; then
  echo "$OK git is installed, continuing with installation..."
  echo "-----"
else
  echo "$ERROR git is not installed, please install git and try again"
  exit 1
fi

echo "$NOTE ensure in home directory"
cd || exit

echo "-----"

backupname=$(date "+%Y-%m-%d-%H-%M-%S")
if [ -d "nixos-config" ]; then
  echo "$NOTE nixos-config exists, backing up to nixos-config-backups directory"
  if [ -d "nixos-config-backups" ]; then
    echo "moving current version of nixos-config to backups directory..."
    sudo mv "$HOME"/nixos-config nixos-config-backups/"$backupname"
    sleep 1
  else
    echo "$NOTE creating the backups directory and moving nixos-config into it..."
    mkdir -p nixos-config-backups
    sudo mv "$HOME"/nixos-config nixos-config-backups/"$backupname"
    sleep 1
  fi
else
  echo "$OK proceeding with installation"
fi

echo "-----"

echo "$NOTE cloning and entering nixos-config repository"
git clone --depth 1 https://g.r-io.lu/shynd/nixos-config.git ~/nixos-config
cd ~/nixos-config || exit

printf "\n%.0s" {1..2}

# check if we're running on a vm and enable option in default config.nix
if hostnamectl | grep -q 'Chassis: vm'; then
  echo "${NOTE} your system is running on a vm, enabling guest services..."
  echo "${WARN} remember to enable 3D acceleration!"
  sed -i '/vm\.guest-services\.enable = false;/s/vm\.guest-services\.enable = false;/ vm.guest-services.enable = true;/' hosts/default/config.nix
fi
printf "\n%.0s" {1..1}

# checking if system has a nvidia gpu and enable option in default config.nix
if command -v lspci > /dev/null 2>&1; then
  # lspci is available, proceed with checking for nvidia gpu
  if lspci -k | grep -A 2 -E "(VGA|3D)" | grep -iq nvidia; then
    echo "${NOTE} nvidia gpu detected, setting up for nvidia drivers..."
    sed -i '/drivers\.nvidia\.enable = false;/s/drivers\.nvidia\.enable = false;/ drivers.nvidia.enable = true;/' hosts/default/config.nix
  fi
fi

echo "-----"
printf "\n%.0s" {1..1}

# aylurs gtk shell v1 installation option
read -p "${CAT} do you want to add ${MAGENTA}AGS or aylur's gtk shell v1${RESET} for desktop overview like? (Y/n): " answer

answer=${answer:-Y}

if [[ "$answer" =~ ^[Nn]$ ]]; then
  sed -i 's|^\([[:space:]]*\)ags.url = "github:aylur/ags/v1";|\1#ags.url = "github:aylur/ags/v1";|' flake.nix
  sed -i 's|^\([[:space:]]*\)ags|\1#ags|' hosts/default/packages-fonts.nix
fi

echo "-----"
printf "\n%.0s" {1..1}

echo "$NOTE default options are in brackets []"
echo "$NOTE just press ${MAGENTA}ENTER${RESET} to select the default"
sleep 1

read -rp "$CAT enter your new hostname: [ default ] " hostName
if [ -z "$hostName" ]; then
  hostName="default"
fi

echo "-----"

# create directory for the new hostname, unless default is used
if [ "$hostName" != "default" ]; then
  mkdir -p hosts/"$hostName"
  cp hosts/default/*.nix hosts/"$hostName"
else
  echo "default hostname selected, no extra host directories created"
fi

echo "-----"

read -rp "$CAT enter your keyboard layout: [ us ] " keyboardLayout
if [ -z "$keyboardLayout" ]; then
  keyboardLayout="us"
fi

sed -i 's/keyboardLayout\s*=\s*"\([^"]*\)"/keyboardLayout = "'"$keyboardLayout"'"/' ./hosts/$hostName/variables.nix

echo "-----"

installusername=$(echo $USER)
sed -i 's/username\s*=\s*"\([^"]*\)"/username = "'"$installusername"'"/' ./flake.nix

echo "${NOTE} generating the hardware configuration..."
attempts=0
max_attempts=3
hardware_file="./hosts/$hostName/hardware.nix"

while [ $attempts -lt $max_attempts ]; do
  sudo nixos-generate-config --show-hardware-config > "$hardware_file" 2>/dev/null

  if [ -f "$hardware_file" ]; then
    echo "${OK} hardware configuration successfully generated"
    break
  else
    echo "${WARN} failed to generate hardware configuration. attempt $(($attempts + 1)) of $max_attempts"
    attempts=$(($attempts + 1))

    # exit if this was the last attempt
    if [ $attempts -eq $max_attempts ]; then
      echo "${ERROR} unable to generate hardware configuration after $max_attempts attempts!"
      exit 1
    fi
  fi
done

echo "-----"

echo "${NOTE} setting required nix settings before proceeding with install"
git config --global user.name "installer"
git config --global user.email "installer@local.domain"
git add .
sed -i 's/host\s*=\s*"\([^"]*\)"/host = "'"$hostName"'"/' ./flake.nix

printf "\n%.0s" {1..2}

echo "${NOTE} rebuilding nixos, this will take some time..."
echo "-----"
printf "\n%.0s" {1..2}


# set the nix configuration for experimental features
NIX_CONFIG="experimental-features = nix-command flakes"
# sudo nix flake update
sudo nixos-rebuild switch --flake ~/nixos-config/#"${hostName}"

echo "-----"
printf "\n%.0s" {1..2}

# for initial zsh
# check if ~/.zshrc exists, create a backup, and copy the new configuration
if [ -f "$HOME/.zshrc" ]; then
  cp -b "$HOME/.zshrc" "$HOME/.zshrc-backup" || true
fi

# copy the preconfigured zsh themes and profile
cp -r 'assets/.zshrc' ~/

echo "-----"
printf "\n%.0s" {1..2}

# gtk themes and icons installation
echo "${NOTE} installing gtk-themes and icons..."

if [ -d "nixos-themeing" ]; then
  echo "${NOTE} gtk themes and icons folder exists, deleting..."
  rm -rf "nixos-themeing"
fi

echo "${NOTE} cloning gtk themes and icons repository..."
if git clone --depth 1 https://g.r-io.lu/shynd/nixos-themeing.git ; then
  cd nixos-themeing
  chmod +x auto-extract.sh
  ./auto-extract.sh
  cd ..
  echo "${OK} extracted gtk themes and icons to ~/.icons and ~/.themes folders"
else
  echo "${ERROR} failed to download gtk themes and icons repository!"
fi

echo "-----"
printf "\n%.0s" {1..2}

# check for existing configs and copy if does not exist
for DIR1 in gtk-3.0 Thunar xfce4; do
  DIRPATH=~/.config/$DIR1
  if [ -d "$DIRPATH" ]; then
    echo -e "${NOTE} config for $DIR1 found, no need to copy"
  else
    echo -e "${NOTE} config for $DIR1 not found, copying from assets..."
    cp -r assets/$DIR1 ~/.config/ && echo "${OK} copy $DIR1 completed!" || echo "${ERROR} error: failed to copy $DIR1 config files!"
  fi
done

echo "-----"
printf "\n%.0s" {1..3}

# clean up
#gtk themes and icons
if [ -d "nixos-themeing" ]; then
  echo "${NOTE} gtk themes and icons folder exists, deleting..."
  rm -rf "nixos-themeing"
fi

echo "-----"
printf "\n%.0s" {1..3}

# cloning hyprland dotiles to home folder
echo "${NOTE} downloading and installing nixos-dots..."
if [ -d ~/nixos-dots ]; then
  cd ~/nixos-dots
  git stash
  git pull
  git stash apply
  chmod +x copy.sh
  ./copy.sh
else
  if git clone --depth 1 https://g.r-io.lu/shynd/nixos-dots ~/nixos-dots; then
    cd ~/nixos-dots || exit 1
    chmod +x copy.sh
    ./copy.sh
  else
    echo -e "${ERROR} could not download nixos-dots!"
    exit 1
  fi
fi

# return to nixos-config directory
cd ~/nixos-config

if [ ! -f "$HOME/.config/fastfetch/nixos.png" ]; then
  cp -r assets/fastfetch "$HOME/.config/"
fi

printf "\n%.0s" {1..2}

if command -v Hyprland &> /dev/null; then
  printf "\n${OK} installation completed!${RESET}\n"
  sleep 2
  printf "\n${NOTE} you can start Hyprland by typing Hyprland (note the capital H)${RESET}\n"
  printf "\n${NOTE} it is highly recommended to reboot your system${RESET}\n\n"

  # prompt user to reboot
  read -rp "${CAT} would you like to reboot now? (y/n): ${RESET}" HYP

  if [[ "$HYP" =~ ^[Yy]$ ]]; then
    # if user confirms, reboot the system
    systemctl reboot
  else
    # print a message if the user does not want to reboot
    echo "${OK} reboot skipped"
  fi
else
  # print error message if Hyprland is not installed
  printf "\n${WARN} Hyprland failed to install, please check install log files...${RESET}\n\n"
  exit 1
fi