#!/usr/bin/env bash

# Installs user preferences the way I like it

# Configuration
function prompt { # text
    while true; do
        read -p "$1 [yn] " yn
        case $yn in
            [Yy]* ) return 1;;
            [Nn]* ) return 0;;
            * ) echo "Please answer yes or no.";;
        esac
    done
}

# Don't ask for things that are already there
TERMUX=0
if [ -d /data/data/com.termux/files ]; then
    TERMUX=1
    GUI=0
fi

if which i3 &> /dev/null; then
    GUI=1
fi

if [ -z $ADMIN ]; then
    prompt "Are you a superuser on this machine?"
    ADMIN=$?
fi
if [ -z $GUI ]; then
    prompt "Do you want a X environment on this machine?"
    GUI=$?
fi
if [ -z $EXTRA ]; then
    prompt "Do you want not-so-needed software on this machine?"
    EXTRA=$?
fi

# TODO Verify if the package exists before installing it

# System detection
if which pacman &> /dev/null; then
    ARCH=1
    if [ $ADMIN == 1 ]; then
        sudo pacman -Sy
        function installOne { # package
            pacman -Q $1 &> /dev/null
            if [ $? == 1 ]; then
                sudo pacman -S $1 --noconfirm --needed
            fi
        }
        function installFileOne { # file
            sudo pacman -U "$1"
        }
        if which pacaur &> /dev/null; then
            function altInstallOne { # package
                pacman -Q $1 &> /dev/null
                if [ $? == 1 ]; then
                    pacaur -S "$1" --noconfirm --noedit
                fi
            }
        elif which yaourt &> /dev/null; then
            function altInstallOne { # package
                pacman -Q $1 &> /dev/null
                if [ $? == 1 ]; then
                    yaourt -S "$1" --noconfirm
                fi
            }
        else
            # Install package from PKGBUILD file
            function installPKGBUILD { # url
                TMP_DIR="$(mktemp -d /tmp/pkgbuild.XXXXXXXXXX)"
                cd "$TMP_DIR"
                wget "$1" -O PKGBUILD
                makepkg -si
                cd -
                rm -rf "$TMP_DIR"
            }

            function altInstallOne { # package
                pacman -Q $1 &> /dev/null
                if [ $? == 1 ]; then
                    installPKGBUILD "https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=$1"
                fi
            }
        fi
    else
        echo "You're on a Arch System but it's not yours? Did Arch got that popular?"
        return 42
    fi

elif which dpkg &> /dev/null; then
    DEBIAN=1
    if [[ $ADMIN == 1 || $TERMUX == 1 ]]; then
        if [ $TERMUX == 1 ]; then
            DEBIAN=0
            apt update -y
        else
            sudo apt-get update -y
        fi
        function installOne { # package

            # Finding out if it's already installed or not
            STATUS=$(mktemp)
            LANG=C dpkg-query --status $1 &> $STATUS
            installed=0
            if [ $? == 0 ]; then
                cat $STATUS | grep '^Status:' | grep ' installed' --quiet
                if [ $? == 0 ]; then
                    installed=1
                fi
            fi
            rm -f $STATUS > /dev/null

            # Installing if it's not installed
            if [ $installed == 0 ]; then
                # TODO noconfirm
                if [ $TERMUX == 1 ]; then
                    apt install $1 -y
                else
                    sudo apt-get install $1 -y
                fi
            fi
        }
        function installFileOne { # file
            dpkg -i "$1"
        }
    else
        function installOne { # package
            debloc install $1
        }
        function installFileOne { # file
            debloc deb "$1"
        }
    fi
    function altInstallOne {
        echo "[ERROR] There's no alternate installer for this distribution. Can't install $1."
    }
else
    echo "Uuuh, what kind of distribution is this?"
    return 1
fi

# Install package with the standard
# package manager for the distribution
function inst {
    for pkg in $*; do
        installOne $pkg
    done
}

# Install package FILE with the standard
# package manager for the distribution
function instFile {
    for pkg in $*; do
        installFileOne $pkg
    done
}

# Install package with the alternate
# package manager for the distribution
function altInst {
    for pkg in $*; do
        altInstallOne $pkg
    done
}

function systemdUserUnit {
    systemctl enable "$1"
    systemctl start "$1"
}

# Common CLI


# Utils
inst coreutils man openssl-tool grep sed sh tar
if [ $TERMUX == 1 ]; then
    inst termux-api
    if [ $ADMIN == 1 ]; then
        inst tsu
    fi
fi
inst moreutils screen ncdu lsof htop proxytunnel pv curl wget netcat mosh bash-completion rsync pwgen fzf highlight
# TODO Test those who are on Debian machines and those who aren't
if [ $ARCH == 1 ]; then
    inst bash-completion tldr
    altInst gopass
else
    inst pass
    wget -qO ~/.bin/ https://raw.githubusercontent.com/pepa65/tldr-bash-client/master/tldr
    chmod +x ~/.bin/tldr
fi
tldr -u
if [[ $ARCH == 1 && $ADMIN == 1 ]]; then
    inst pkgfile
    sudo systemctl enable pkgfile-update.timer
fi

# Dev
if [ $DEBIAN == 1 ]; then
    inst build-essential
elif [ $ARCH == 1 ]; then
    inst base-devel
else
    inst make
fi
inst git 


# Text editor
if [ $TERMUX == 1 ]; then
    inst vim-python
elif [ $DEBIAN == 1 ]; then
    inst vim-nox
    if [ $ADMIN == 0 ]; then
        debloc altern vim nox
    fi
else
    inst vim
fi
if [ $DEBIAN == 1 ]; then
    inst exuberant-ctags
else
    inst ctags
fi
vim +PlugUpgrade +PlugUpdate +PlugInstall +qall

# Common GUI
if [ $GUI == 1 ]; then
    .Xresources.d/configure

    # Desktop manager
    inst i3 i3lock dunst unclutter xautolock feh numlockx scrot rxvt-unicode xclip
    curl "https://raw.githubusercontent.com/FortAwesome/Font-Awesome/a8386aae19e200ddb0f6845b5feeee5eb7013687/fonts/fontawesome-webfont.ttf" > ~/.local/share/fonts/fontawesome-webfont.ttf
    if [ $ARCH == 1 ]; then
        inst xorg-xinit
        altInst polybar-git autorandr-git keynav-enhanced pacmixer
    else
        # Compiling polybar
        if ! which polybar > /dev/null; then
            inst debhelper cmake libxcb-icccm4-dev libxcb-image0-dev libxcb-randr0-dev libx11-dev libxcb1-dev libxcb-util-dev libx11-xcb-dev linux-libc-dev libboost-dev x11proto-core-dev libxcb-ewmh-dev libxft-dev libasound2-dev libiw-dev libmpdclient-dev xcb-proto python-xcbgen libxcb-xkb-dev i3-wm libcairo2-dev libxcb-xrm-dev
            # TODO Figure which one are really needed
            #inst libasound2 libc6 libgcc1 libiw30 libmpdclient2 libstdc++6 libx11-6 libx11-xcb1 libxcb-ewmh2 libxcb-icccm4 libxcb-randr0 libxcb-xkb1 libxcb1 libxft2
            # ↓ really needed
            inst libcairo2-dev libxcb-xkb-dev libxcb-randr0-dev xcb-proto libxcb-image0-dev libxcb-icccm4-dev libxcb-ewmh-dev libxcb-util0-dev python-xcbgen

            TMP=$(mktemp -d)
            git clone --branch 3.0.5 --recursive https://github.com/jaagr/polybar $TMP
            mkdir $TMP/build
            cd $TMP/build
            cmake ..
            make -j`nproc`
            strip bin/polybar
            mv bin/polybar ~/.bin/
            rm -rf $TMP
        fi
    fi
    if [ $DEBIAN == 1 ]; then
        inst suckless-tools keynav
        if [ $ADMIN == 0 ]; then
            debloc altern dmenu xft
        fi
    else
        inst dmenu
    fi
    if [ "$(source /etc/os-release; echo $NAME)" == "Manjaro Linux" ]; then
        inst menda-themes menda-circle-icon-theme xcursor-menda
    fi

    # qutebrowser
    if [ $DEBIAN == 1 ]; then
        inst python3-lxml python-tox python3-pyqt5 python3-pyqt5.qtwebkit python3-pyqt5.qtquick python3-sip python3-jinja2 python3-pygments python3-yaml python3-pyqt5.qtsql libqt5sql5-sqlite python3-pyqt5.qtwebengine python3-pyqt5.qtopengl python3-opengl
        TMP_DIR=$(mktemp -d)
        $(cd $TMP_DIR; wget https://qutebrowser.org/python3-pypeg2_2.15.2-1_all.deb)
        $(cd $TMP_DIR; wget https://github.com/qutebrowser/qutebrowser/releases/download/v0.11.0/qutebrowser_0.11.0-1_all.deb)
        instFile $TMP_DIR/*.deb
        rm -rf $TMP_DIR

    elif [ $ARCH == 1 ]; then
        inst qutebrowser qt5-webengine python-opengl
    fi

    # Screen filter
    if [ $ARCH == 1 ]; then
        altInst sct
    elif [ $TERMUX != 1 ]; then
        if [ ! -f $HOME/.bin/sct ]; then
            TMP=$(mktemp /tmp/XXXXXXXXXX.c)
            wget https://gist.githubusercontent.com/ajnirp/208c03d3aa7f02c743d2/raw/55bf3eed25739173d8be57b5179ed5542cf40ed6/sct.c -O $TMP
            cc $TMP --std=c99 -lX11 -lXrandr -o $HOME/.bin/sct
            rm $TMP
        fi
    fi

    # Graphical vim
    if [ $DEBIAN == 1 ]; then
        inst vim-gtk
    else
        inst gvim
    fi
fi


if [ $EXTRA == 1 ]; then
    # Extra dev
    inst cmake clang llvm npm
    inst python-rope

    # Extra CLI
    inst ffmpeg youtube-dl optipng syncthing ccache mutt
    systemdUserUnit syncthing.service
    if [ $ARCH == 1 ]; then
        inst jq
        altInst pdftk translate-shell git-lfs js-beautify insect visidata-git

        # Orga
        # TODO For others
        inst vdirsyncer khard
        altInst khal todoman offlineimap
        systemdUserUnit vdirsyncer.timer
    else
        # translate-shell
         curl -L git.io/trans > ~/.bin/trans
         chmod +x ~/.bin/trans
    fi

    # Extra GUI
    if [ $GUI == 1 ]; then
        inst vlc gimp mpd thunar noto-fonts-emoji musescore

        if [ $ARCH == 1 ]; then
            inst simplescreenrecorder
            altInst pacmixer xcursor-menda-git menda-themes-git menda-maia-icon-theme vimpc-git mpc ashuffle-git
        fi

    fi
fi