#!/usr/bin/env sh

# List of the software I use divided by categories.
# Oh and it asks the category you want to install on
# the running machine too.

# TODO Not tested with Debian derivate
# TODO Not tested on home folder

CONFIG_FILE="${XDG_CONFIG_DIR:=$HOME/.config}/softwareList"
mkdir -p $XDG_CONFIG_DIR
touch $CONFIG_FILE
. $CONFIG_FILE

prompt() { # text
    res="none"
    while [ "$res" = "none" ]
    do
        printf "%s [yn] " "$1"
        read -r yn
        case $yn in
            [Yy]* ) return 0;;
            [Nn]* ) return 1;;
            * ) echo "Please answer y or n.";;
        esac
    done
}

uservar() {  # var text
    if [ -z "${!1}" ]
    then
        prompt "${2}" && res=true || res=false
        export "$1"="$res"
        echo "$1"="$res" >> "$CONFIG_FILE"
    fi
}

echo "Please answer some questions about this machine and what you want to do on it:"

# Setting variables
[ -d /data/data/com.termux/files ] && TERMUX=true || TERMUX=false
$TERMUX && INSTALL_GUI=false
[ "$USER" = "root" ] && SUPERUSER=true

uservar SUPERUSER "Have root permissions?"
uservar INSTALL_GUI "Install a GUI environment?"
$INSTALL_GUI && INSTALL_X=true
INSTALL_WAYLAND=false
uservar INSTALL_PASSWORD "Handle password?"
uservar INSTALL_MAIL "Read/send mail?"
uservar INSTALL_ORGANISATION "Handle agenda/contacts?"
uservar INSTALL_HOUSEKEEPING "Do some housekeeping?"
uservar INSTALL_FPGA "Handle FPGAs?"
uservar INSTALL_UTILITIES "Extra utilities?"
uservar INSTALL_DOCUMENT "Create documents?"
uservar INSTALL_IMAGE "Do image editing?"
uservar INSTALL_MUSIC "Play/edit music?"
uservar INSTALL_VIDEO "Play/edit videos?"
if $INSTALL_GUI
then
    uservar INSTALL_WINE "Run Windows applications?"
fi

echo "(you can change those answers later in $CONFIG_FILE)"

# Preparing installers
. $HOME/.config/scripts/common/installSoftware

resetInstallers
$SUPERUSER && addSystemInstallers
addUserInstallers

echo "Installers that will be used:"
listInstallers | sed 's/^/- /'

echo "Updating databases & packages"
# updateInstallers # DEBUG put back

echo "Finding packages to install"
# Note: i A B: will try A then B for each installer
#       i A || i B: will try A for each installer, then B for each installer

# Package managers (install first)
i yay
i python-pip python3-pip pip3

# TODO Install first and recharge installers

# Utils used by those scripts
i base coreutils # Basic shell commands (ls, rm, cp...)
i bash # Shell
i grep # Text finder
i sed # Text replacer
i tar # Archive tool
i openssl openssl-tools  # machines script verification

# Various utilities

$SUPERUSER && i sudo tsu
$TERMUX && termux-api

# Shell utilities
i moreutils # Advanced shell commands (ts, sponge...)
i tmux # Terminal multiplexer
i bash-completion # Shell completions
i fzf # Fancy file finder
i highlight # Syntax highlighter

i zsh # Shell
i zsh-autosuggestions # Shell suggestions
i zsh-completions # Shell completions
i zsh-history-substring-search # Shell config
i zsh-syntax-highlighting # Shell highlighting

# Text edition
(i neovim nvim && i python-neovim python3-neovim) || i vim || i vi # Text editor

# Monitoring utilities
i ncdu # Explore directories by weight on disk
i lsof # Find who/what uses the files
i pv # Allow to show progress in pipe

# Network utilities
i openssh # SSH connections
i proxytunnel # Proxy connections through HTTPS
i curl # Transfer URL
i wget # Download URL
i gnu-netcat # Network piping
i socat # Multi-purpose relay
i rsync # Remote file-copying tool
i speedtest-cli # Network speed benchmarker
i bind-tools # DNS queryier

# Archives utilities
i unzip # Unarchive ZIP files
i unrar # Unarchive RAR files
i p7zip # Unarchive 7z files

# Password handling
if $INSTALL_PASSWORD
then
    i pwgen # Password generator
    i gopass || i pass # Password manager
    if $INSTALL_GUI
    then
        i rofi-pass # Password selector
    fi
fi

if $INSTALL_MAIL
then
    # i offlineimap # Synchronize IMAP (legacy)
    i isync mbsync # Synchronize IMAP
    i msmtp # Send mail via SMTP
    i notmuch # Index mail
    i neomutt || i mutt # CLI mail client
    i lynx # CLI web browser (for HTML mail)
    i tiv # CLI image viewer
    if $INSTALL_GUI
    then
        i thunderbird # GUI mail client (just in case)
    fi
fi

if $INSTALL_ORGANISATION
then
    i vdirsyncer # Synchronize DAV
    i khard # Contacts editor
    i khal # Calendar editor
    i task # Todo-list
    i timew # Time-tracker
fi


if $INSTALL_HOUSEKEEPING
then
    i syncthing # Synchronize files amongst devices
    i jdupes # Find duplicates
    i duperemove # Find and merge dupplicates on BTRFS partitions
    i optipng # Optimize PNG files
    i jpegtran libjpeg-turbo # Compress JPEG files
    i reflac # Recompress FLAC files
    i pacman-contrib # Pactree and more
    i shred # Delete sensititve data
fi



# Dev utilities
i base-devel build-essential || (i make; i gcc)
i git
[ -z "$INSTALL_DEV" ] && $TERMUX && INSTALL_DEV=false
if $INSTALL_DEV
then
    # Misc/Reusable
    i man # Documentation
    i strace # Tracer
    i ctags universal-ctags exuberant-ctags # Tags generator

    # C/C++
    i cmake # C++ Build system
    i clang # C/C++ Compiler
    i ccache # Build cache
    i gdb # Debugger

    # JS
    i jq # CLI JSON file handler

    # Python
    i python-language-server # Python language server
    i mypy && i pyls-mypy # Static typing checker for Python

    # Bash
    i bash-language-server # Bash / SH language server
fi


if $INSTALL_FPGA
then
    i yosys # Verilog processor
    i iverilog # Verilog simulator
    i ghdl # VHDL simulator
    i gtkwave # Simulation file viewer
fi

if $INSTALL_UTILITIES
then
    i visidata # CSV file reader
    i insect # Unit calculator
    i zbar # Read QR codes
    i htop # View process usage
    $SUPERUSER && i iotop # View process I/O
    i progress # Show progress of functions
fi


if $INSTALL_DOCUMENT
then
    i pandoc # Document converter
    i texlive-most && i texlive-lang # LaTeX renderer
    i pdftk # PDF manipulator
    i translate-shell # Translator
    i inkscape # Vector image converter
    i optipng # Optimize PNG files
    i jpegtran libjpeg-turbo # Compress JPEG files
fi

if $INSTALL_IMAGE
then
    i imagemagick # CLI Image manipulator
    i gimp # Photo editor
    i darktable # Raw photo editor
    i inkscape # Vectorial image editor
    i optipng # Optimize PNG files
    i jpegtran libjpeg-turbo # Compress JPEG files
fi

if $INSTALL_MUSIC
then
    i mpv # Audio/Video player
    i puddletag-qt5-git puddletag # Musig tag editor
    # (remove -qt5 once it has been merged upstream)
    i mpd # Music player daemon
    i mpc # CLI MPD client
    i vimpc-git # CLI UI MPD client
    i musescore # Music sheet editor
    i ashuffle # Auto-fill MPD playlist
fi


if $INSTALL_VIDEO
then
    i vlc # Video player
    i mpv # Audio/Video player
    i ffmpeg # Video/Audio file handler
    i youtube-dl # Downloader for videos
    i megatools # Downloader for mega.nz
    if $INSTALL_X
    then
        i simplescreenrecorder # Screen recorder
    fi
fi

if $INSTALL_WINE
then
    # TODO Add multilib repo and pacman -Sy
    i wine # Wine
    i wine-gecko # Wine Internet Explorer
    i wine-mono # Wine .NET
    i mono # Mono .NET
    i lib32-libpulse # Sound for Wine with pulseaudio
fi

# Desktop environment
if $INSTALL_GUI
then
    i firefox # Web browser
    i firefox-dark-reader # Firefox extension: dark theme everywhere
    i firefox-decentraleyes # Firefox extension: fetch CDN resources locally
    i firefox-tridactyl # Firefox extension: Navigate with keyboard
    i firefox-ublock-origin # Firefox extension: Ad and tracker blocker
    # I still need to download manually: container extensions, No Tab

    i xkb-qwerty-fr # French QWERTY disposition
    i thunar # Directory browser (just in case)
    i gedit # Visual editor (just in case)
    i feh # Background / Image viewer
    i zathura && i zathura-pdf-mupdf # PDF viewer
    i ttf-dejavu # Font
    i ttf-twemoji # Emoji fonts
    i adobe-source-han-sans-otc-fonts # Chinese/Japanese/Korean fonts
    i sox # For beeps and stuff
    i meld # For comparison

    if $INSTALL_X
    then
        i i3-wm # WM
        i libgnomekbd # Show keyboard layout
        i dunst # Notifications
        i i3lock # Locker
        i numlockx # Numlock auto-unlock
        i rofi # HUD selector
        i rxvt-unicode # Terminal emulator
        i urxvt-resize-font-git # Resize fonts for urxvt
        i scrot # Screenshot taker
        i trayer  # Tray icons (just in case)
        i unclutter # Auto mask mouse
        i xautolock # Auto lock screen
        i xclip # Copy/paste
        i lemonbar-xft-git lemonbar # Bottom bar
        i autorandr # Multiple screen configurations
        i keynav-enhanced keynav # Use mouse with keyboard
        i pacmixer # To change PA volumes
        i sct # Red filter # TODO Autocompile

        i xorg-xinit # To launch X
        i xorg-xbacklight xbacklight # For laptop brightness
        i pulseaudio # To get ausdio
        # TODO Bluetooth headset stuff

    fi

    if $INSTALL_WAYLAND
    then
        i sway
    fi
fi

echo "Listing software to install"

listInstallers | while read -r installerName
do
    echo " Installer $installerName will install:"
    listPackagesForInstaller "$installerName" | sed 's/^/ - /'
done

prompt "Okay with those?" || exit 0

echo "Installing packages"

installPackages