#!/usr/bin/env bash

if [ "$(id -u)" -eq 0 ]; then 
    printf "Don't run this script as root!" 
    exit 1
else 
    printf "not root"
fi

GREEN="$(tput setaf 2)[OK]$(tput sgr0)"
RED="$(tput setaf 1)[ERROR]$(tput sgr0)"
YELLOW="$(tput setaf 3)[NOTE]$(tput sgr0)"
CAT="$(tput setaf 6)[ACTION]$(tput sgr0)"
BOLD=$(tput bold)
NORMAL=$(tput sgr0)
clear
LOG="install.log"
HYPRMOONARCH_DIR=$PWD



set -e

function pkg_inst () {
    log "Checking if $1 is installed..."
    if pacman -Qs $1; then
        log "Found $IS_INSTALLED ...skipping"
    else
        log "$1 not found. Installing..."
        paru -S $1 2>&1 | tee -a $LOG
    fi
}

function inst_ufw {
    echo "-"
    echo "Install ${BOLD}Firewall${NORMAL} and set some common rules"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_ufw
    if [[ $confirm_ufw == "Y" ]]; 
    then
        declare -a pkg_list=(ufw gufw)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done

        sudo ufw enable
        sudo systemctl enable ufw
        sudo ufw default deny incoming
        sudo ufw allow http
        sudo ufw allow https
        sudo ufw allow ssh
        sudo ufw allow ntp
        sudo ufw allow 67:68/tcp
        sudo ufw allow 53
    fi
}

function inst_zsh {
    echo "-"
    echo "Installing ${BOLD}ZSH${NORMAL}"
    echo "Installs ZSH + Autosuggestions and set zsh as your default shell"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_zsh
    if [[ $confirm_zsh == "Y" ]]; 
    then
        declare -a pkg_list=(zsh oh-my-zsh)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done
   
        cp -rf $HYPRMOONARCH_DIR/home/.zshrc $HOME/.zshrc
        chown $USER:$USER $HOME/.zshrc

        sudo git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
        sudo git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
        sudo git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k
        chsh -s /usr/bin/zsh

        cp -rf $HYPRMOONARCH_DIR/home/.p10k.zsh $HOME/.p10k.zsh
    fi
}

function inst_basic_pkgs {
    log "-"
    log "Installing ${BOLD}recommended packages.${NORMAL}"
    log "This can include dependencies on other things. You definitely want this."
    log "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_basics
    log "$confirm_basics"
    if [[ $confirm_basics == "Y" ]]; 
    then

        declare -a pkg_list=(jq network-manager-applet alarm-clock-applet man-db hardinfo networkmanager-openvpn udisks2 plocate vim alacritty gettext-hostname neovim lsd alsa-utils ponymix btop powertop polkit polkit-gnome timeshift timeshift-autosnap pcmanfm librewolf-bin fzf)

        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done

        sudo cp $HYPRMOONARCH_DIR/usr/local/bin/volnote /usr/local/bin

        cp -Rf $HYPRMOONARCH_DIR/home/config/alacritty $HOME/.config/alacritty
        chown $USER:$USER $HOME/.config/alacritty

        cp -Rf $HYPRMOONARCH_DIR/home/config/btop $HOME/.config/btop
        chown $USER:$USER $HOME/.config/btop

        cp -Rf $HYPRMOONARCH_DIR/home/config/lsd $HOME/.config/lsd
        chown $USER:$USER $HOME/.config/lsd

        paru -S informant
        sudo informant read --all

    fi
}

function inst_paru {
    echo "-"
    echo "Installing AUR helper ${BOLD}paru${NORMAL}?"
    echo "${BOLD}paru${NORMAL} is mandatory."

    if command -v paru > /dev/null 2>&1; then
        echo "${BOLD}paru ${NORMAL}already installed. Skipping..."
    else
        echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
        read confirm_paru 2>&1 | tee -a $LOG
        if [[ $confirm_paru == "Y" ]]; 
        then
            sudo pacman -Syu --needed base-devel 2>&1 | tee -a $LOG
            sudo pacman -Syu rustup 2>&1 | tee -a $LOG
            rustup default stable 2>&1 | tee -a $LOG
            rustup update

            rm -rf $HYPRMOONARCH_DIR/.cache/paru-git
            git clone https://aur.archlinux.org/paru.git $HYPRMOONARCH_DIR/.cache/paru-git
            cd $HYPRMOONARCH_DIR/.cache/paru-git
            makepkg -si
            cd $HYPRMOONARCH_DIR

            git pull

            mkdir -p $HOME/.local/bin
            echo 'PATH="$HOME/.local/bin:$PATH"' | sudo tee -a /etc/environment >/dev/null

        else
            echo "exiting"
            exit 1
        fi
    fi
}

function post_always {
    
    echo " "
    echo " "
    echo " "

    echo "-"
    echo "Running updatedb"
    sudo updatedb
    echo " "
    echo " "
    echo " "
    echo "Here are some optional packages... "
    echo "ungoogled-chromium"
    echo "filezilla"
    echo "lutris"

    echo " "
    echo " "
    echo " "
    echo "If you didn't pick the Noise Suppression check NoiseTorch."
    echo "Goodbye"
}

function inst_bluet {
    echo "-"
    echo "Installing ${BOLD}Bluetooth${NORMAL} Support"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_bluet
    if [[ $confirm_bluet == "Y" ]]; 
    then
        declare -a pkg_list=(bluez bluez-utils-compat blueberry)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done
  
        sudo systemctl start bluetooth.service
        sudo systemctl enable bluetooth.service
    fi
}

function inst_noise_supr {
    echo "-"
    echo "Installing ${BOLD}Noise Suppression for voice${NORMAL}"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_noise_supr
    if [[ $confirm_noise_supr == "Y" ]]; 
    then
        declare -a pkg_list=(noise-suppression-for-voice)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done

        mkdir -p $HOME/.config/pipewire/pipewire.conf.d/
        cp -f $HYPRMOONARCH_DIR/home/config/pipewire/pipewire.conf.d/99-input-denoising.conf $HOME/.config/pipewire/pipewire.conf.d/99-input-denoising.conf

        systemctl restart --user pipewire.service
    fi

}

function inst_clamav {
    echo "-"
    echo "Installing ClamAV - Anti-Virus Scanner with freshclam and fangfrisch"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_clamav
    if [[ $confirm_clamav == "Y" ]]; 
    then
        declare -a pkg_list=(clamav python-fangfrisch)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done

        sudo systemctl start clamav-daemon.service
        sudo systemctl enable clamav-daemon.service
        sudo freshclam
        sudo -u clamav /usr/bin/fangfrisch --conf /etc/fangfrisch/fangfrisch.conf initdb
        sudo systemctl enable fangfrisch.timer

        if command -v nemo &> /dev/null
        then
            cp -Rf $HYPRMOONARCH_DIR/usr/share/nemo/actions/clamscan.nemo_action /usr/share/nemo/actions
        fi

    fi
}

function set_gui {
    echo "-"
    echo "Setting up GUI "
    echo "Including window decoration, Fonts, GTK Theming, Wallpaper and some convenient GUI applications"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_gui
    if [[ $confirm_gui == "Y" ]]; 
    then
        declare -a pkg_list=(celluloid playerctl audacious font-manager viewnior tumbler ffmpegthumbnailer pavucontrol ttf-hack-nerd ttf-joypixels sweet-cursor-theme-git catppuccin-gtk-theme-mocha flatery-icon-theme-git)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done 

        cp -Rf $HYPRMOONARCH_DIR/home/config/gtk-3.0 $HOME/.config/gtk-3.0
        chown $USER:$USER $HOME/.config/gtk-3.0

        cp -Rf $HYPRMOONARCH_DIR/home/config/gtk-4.0 $HOME/.config/gtk-4.0
        chown $USER:$USER $HOME/.config/gtk-4.0

        install $HYPRMOONARCH_DIR/home/config/gtk-3.0/settings.ini $HOME/.config/gtk-3.0/settings.ini
        install $HYPRMOONARCH_DIR/home/config/gtk-4.0/settings.ini $HOME/.config/gtk-4.0/settings.ini

        gsettings set org.gnome.desktop.interface gtk-theme "catppuccin-mocha-lavender-standard+default-dark"
        gsettings set org.gnome.desktop.interface color-scheme 'prefer-dark'
        gsettings set org.gnome.desktop.interface cursor-theme Sweet-cursors

        xdg-mime default pcmanfm.desktop inode/directory
        #gsettings set org.cinnamon.desktop.default-applications.terminal exec alacritty

        sudo mkdir -p /usr/local/share/fonts/
        sudo install -C $HYPRMOONARCH_DIR/usr/local/share/fonts/MonarchOS.ttf /usr/local/share/fonts/MonarchOS.ttf
        sudo install -C $HYPRMOONARCH_DIR/usr/local/share/fonts/Icomoon-Feather.ttf /usr/local/share/fonts/Icomoon-Feather.ttf
        sudo install -C $HYPRMOONARCH_DIR/etc/fonts/local.conf /etc/fonts/local.conf
        fc-cache -f

        WALLPAPER_DIR=$HOME/Pictures/Wallpaper
        if [ ! -d "$WALLPAPER_DIR" ]; then
            mkdir -p $WALLPAPER_DIR
        fi
        install -C $HYPRMOONARCH_DIR/home/Pictures/Wallpaper/MonarchOS.png $WALLPAPER_DIR/MonarchOS.png
    fi
}

function inst_rofi {
    echo "-"
    echo "Installing Rofi - Application launcher"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_rofi
    if [[ $confirm_rofi == "Y" ]]; 
    then
        declare -a pkg_list=(rofi-lbonn-wayland-git)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done 

        cp -Rf $HYPRMOONARCH_DIR/home/config/rofi $HOME/.config/rofi
        chown $USER:$USER $HOME/.config/rofi

        sudo cp -Rf $HYPRMOONARCH_DIR/usr/share/settings-menu /usr/share/settings-menu

        cargo install --git=https://github.com/nate-sys/hypr-empty
        cp -Rf $HYPRMOONARCH_DIR/home/config/hypr-empty $HOME/.config/hypr-empty

    fi
}

function inst_code {
    log "-"
    log "Installing Visual Studio Code (Codium)"
    log "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_vscode
    log "$confirm_vscode"
    if [[ $confirm_vscode == "Y" ]]; 
    then
        declare -a pkg_list=(vscodium-bin)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done 

        log "Installing VSCode Extensions"

        codium --install-extension catppuccin.catppuccin-vsc-pack | tee -a $LOG
        codium --install-extension Catppuccin.catppuccin-vsc-icons | tee -a $LOG
        codium --install-extension Catppuccin.catppuccin-vsc | tee -a $LOG
        codium --install-extension smcpeak.default-keys-windows | tee -a $LOG
    fi
}

function inst_screenshot {
    log "-"
    log "Installing utilities to have a nice screenshot annoation tool"
    log "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_screenshot
    log "$confirm_screenshot"
    if [[ $confirm_screenshot == "Y" ]]; 
    then
        declare -a pkg_list=(satty-bin grim slurp)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done 

        sudo cp -Rf $HYPRMOONARCH_DIR/usr/local/bin/hyprm-screenshot /usr/local/bin/
    fi
}

function inst_hypr {
    echo "-"
    echo "Installing Wayland 'Desktop' - Hyprland based system"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_hypr
    if [[ $confirm_hypr == "Y" ]]; 
    then
        declare -a pkg_list=(wayland hyprland hypridle hyprlock hyprcursor hyprkeys hyprpicker swww waypaper xdg-desktop-portal-hyprland wdisplays waybar nwg-look cliphist wlogout swayosd hyprlock waybar-module-pacman-updates swaync)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done

        sudo cp -Rf $HYPRMOONARCH_DIR/etc/wlogout/style.css /etc/wlogout/style.css
        sudo cp -Rf $HYPRMOONARCH_DIR/etc/wlogout/layout /etc/wlogout/layout

        cp -Rf $HYPRMOONARCH_DIR/home/config/swaync $HOME/.config/swaync
        chown $USER:$USER $HOME/.config/swaync

        cp -Rf $HYPRMOONARCH_DIR/home/config/hypr $HOME/.config/hypr
        chown $USER:$USER $HOME/.config/hypr
        cp -Rf $HYPRMOONARCH_DIR/home/config/waybar $HOME/.config/waybar
        chown $USER:$USER $HOME/.config/waybar

        if [ -z "$HYPRLAND_INSTANCE_SIGNATURE" ] 
        then 
            log "Hyprland not running, can't set cursor"
        else
            hyprctl setcursor Sweet-cursors 16
        fi

        cp -Rf $HYPRMOONARCH_DIR/home/config/waypaper $HOME/.config/waypaper
        chown -R $USER:$USER $HOME/.config/waypaper
        sed -i "s|USERNAME|${USER}|g" $HOME/.config/waypaper/config.ini
        if [ -z "$HYPRLAND_INSTANCE_SIGNATURE" ] 
        then
             log "Hyprland not running, can't set wallpaper"
        else
            swww-daemon &
            swww img $WALLPAPER_DIR/MonarchOS.png
        fi
    fi
}

function inst_bspwm {
    echo "-"
    echo "Installing X11 - bspwm based system"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_bspwm
    if [[ $confirm_bspwm == "Y" ]]; 
    then
        declare -a pkg_list=(bspwm sxhkd picom-arian8j2-git polybar xdg-desktop-portal)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done

        cp -Rf $HYPRMOONARCH_DIR/home/config/bspwm $HOME/.config/bspwm
        chown $USER:$USER $HOME/.config/bspwm

        cp -Rf $HYPRMOONARCH_DIR/home/config/sxhkd $HOME/.config/sxhkd
        chown $USER:$USER $HOME/.config/sxhkd

        cp -Rf $HYPRMOONARCH_DIR/home/config/picom $HOME/.config/picom
        chown $USER:$USER $HOME/.config/picom

        cp -Rf $HYPRMOONARCH_DIR/home/config/polybar $HOME/.config/polybar
        chown $USER:$USER $HOME/.config/polybar
    fi
}

function inst_conky {
    echo "-"
    echo "Installing Conky - light-weight system monitor widgets"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_conky
    if [[ $confirm_conky == "Y" ]]; 
    then
        declare -a pkg_list=(conky)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done

        cp -Rf $HYPRMOONARCH_DIR/home/config/conky $HOME/.config/conky
        chown $USER:$USER $HOME/.config/conkys
    fi
}

function inst_sddm {
    echo "-"
    echo "Installing SDDM - Fancy Display/Login Manager"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_sddm
    if [[ $confirm_sddm == "Y" ]]; 
    then
        declare -a pkg_list=(sddm qt5-quickcontrols qt5-graphicaleffects qt6-svg qt6-declarative)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done

        log "REMEMBER: this will fail if you don't disable any other display manager before"

        # log "clear package cache"
        # rm -rf $HOME/.cache/Elegant-sddm-monarch
        # log "clone sddm theme"
        # git clone https://gitea.nevaforget.de/dom/Elegant-sddm-monarch/ $HOME/.cache/Elegant-sddm-monarch
        # log "copy sddm theme to destination"
        # sudo cp -rf $HOME/.cache/Elegant-sddm-monarch/Elegant /usr/share/sddm/themes/monarch
        # log "set current sddm theme"
        # sudo cp -rf /usr/lib/sddm/sddm.conf.d/default.conf /etc/sddm.conf
        # sudo sed -i "s/^Current=.*/Current=monarch/g" /etc/sddm.conf

        log "set default user image"
        sudo cp -f $HYPRMOONARCH_DIR/usr/share/sddm/faces/.face /usr/share/sddm/faces/.face
        cp -f $HYPRMOONARCH_DIR/usr/share/sddm/faces/.face $HOME/.face


        cd $HYPRMOONARCH_DIR/.cache
        wget --unlink https://github.com/catppuccin/sddm/releases/download/v1.0.0/catppuccin-mocha.zip
        sudo unzip catppuccin-mocha.zip -d /usr/share/sddm/themes/
        cd $HYPRMOONARCH_DIR
        sudo sed -i "s/^Current=.*/Current=catppuccin-mocha/g" /etc/sddm.conf

        sudo systemctl enable sddm
    fi
}

function inst_nemo {
    echo "-"
    echo "Installing Nemo - Cinnamon File Manager with extensions"
    echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
    read confirm_nemo
    if [[ $confirm_nemo == "Y" ]]; 
    then
        declare -a pkg_list=(nemo nemo-fileroller nemo-mediainfo-tab nemo-audio-tab cinnamon-translations)
        for key in "${pkg_list[@]}"
        do
            pkg_inst $key
        done

        xdg-mime default nemo.desktop inode/directory application/x-gnome-saved-search
        gsettings set org.nemo.desktop show-desktop-icons false
        gsettings set org.cinnamon.desktop.default-applications.terminal exec alacritty
        gsettings set org.cinnamon.desktop.interface can-change-accels true
    fi
}

function log () {
    ts=$(date +"%H:%M:%S")

    printf "$ts $1\n" | tee -a $LOG
}

function init {

    rm -f $LOG

    mkdir $HYPRMOONARCH_DIR/.cache

    log "Installation start\n"

    inst_paru

    type paru >/dev/null 2>&1 || { echo >&2 "I require paru but it's not installed.  Aborting."; exit 1; }

    inst_basic_pkgs

    inst_sddm    
    inst_hypr
    inst_bspwm
    set_gui

    inst_rofi
    inst_nemo
    inst_zsh

    inst_ufw
    inst_clamav
    inst_noise_supr
    

    inst_bluet
    inst_screenshot
    inst_code
    
    post_always
}

printf "#####################################\n"
printf "$(tput setaf 2)Welcome to MoonArch. Feel free.\n@version 1.0\n$(tput sgr0)"
printf "#####################################\n"
printf "\n"
printf "$(tput setaf 2)Don't run this script as ROOT!\n$(tput sgr0)"
printf "\n"
printf "${YELLOW} ${BOLD}This will clear and overwrite some config files\nand this can not be reverted. No Backups are created!\n " 
printf "\n"
echo -n "${BOLD}Continue?${NORMAL} (Y/N) "
read confirm

if [[ $confirm == "Y" ]]; 
then
    init
else
    echo "Goodbye sweet butterfly"
    exit 1
fi