#!/usr/bin/env bash

###################################################################################
#
# /!\ WARNING /!\
#
# If you want to use this script, be sure to read all and adjust it to your needs
# For example, I add my name and my email adress to git global config, change it!
#
###################################################################################

_success() {
    echo -e "\e[1;32m$1\e[0m"
}

_error() {
    echo -e "\e[1;41;37m$1\e[0m"
}

_info() {
    echo -e "\e[0;37m$1\e[0m"
}

commandExists() {
    command -v "$1" > /dev/null 2>&1
}

installPackage() {
    if [[ "$2" = "" ]]; then
        local packages="$1"
    else
        local packages="$2"
    fi

    if commandExists "$1"; then
        _info "$1 is already installed"
        return
    fi

    echo -n "Installing $packages... "
    sudo apt-get install -q -y $packages >> post_install.log 2>&1 &
    local pid=$!
    spinner $pid
    wait $pid
    if test $? -eq 0; then
        _success "OK"
    else
        _error "Error installing $packages. See post_install.log"
    fi
}

confirm() {

    local choices
    local question
    local defaultResponse

    case "$1" in
        "-y")
            choices="Yn"
            question="$2"
            defaultResponse=0
            ;;
        "-n")
            choices="yN"
            question="$2"
            defaultResponse=1
            ;;
        *)
            choices="yn"
            question="$1"
            ;;
    esac

    while true; do

        read -ep "$question [$choices]: " userChoice

        case $userChoice in
            [yY]* ) return 0;;
            [nN]* ) return 1;;
            "" ) if [[ "$defaultResponse" != "" ]]; then return $defaultResponse; fi;;
        esac
    done
}

# Courtesy of http://fitnr.com/showing-file-download-progress-using-wget.html
download()
{
    local url=$1
    echo -n "    "
    wget -P /tmp --progress=dot $url 2>&1 | grep --line-buffered "%" | \
        sed -u -e "s,\.,,g" | awk '{printf("\b\b\b\b%4s", $2)}'
    echo -ne "\b\b\b\b"
    _success "OK"
}

# Courtesy of http://fitnr.com/showing-a-bash-spinner.html
spinner()
{
    local pid=$1
    local delay=0.75
    local spinstr='|/-\'
    while [ "$(ps a | awk '{print $1}' | grep $pid)" ]; do
        local temp=${spinstr#?}
        printf " [%c]  " "$spinstr"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
        printf "\b\b\b\b\b\b"
    done
    printf "    \b\b\b\b"
}

echo "" > post_install.log

sudo echo ""
echo "+--------------------------------+"
echo "+                                +"
echo "+ WELCOME TO POST INSTALL SCRIPT +"
echo "+                                +"
echo "+--------------------------------+"
echo ""

read -ep "Enter PhpStorm file URL to install/update it: " phpstormUrl
read -ep "Enter WebStorm file URL to install/update it: " webstormUrl
read -ep "Enter Mongochef file URL to install/update it: " mongochefUrl

declare -a directories=("$HOME/Applications" "$HOME/Development/Php" "$HOME/Development/Meteor" "$HOME/Development/AngularJS")

for dir in "${directories[@]}"; do
    if [[ ! -d "$dir" ]]; then
        echo -n "Creating $dir directory... "
        mkdir -p "$dir" >> post_install.log 2>&1 &
        spinner $!
        _success "OK"
    fi
done

echo -n "Adding/Updating Google Chrome APT repository... "
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - >> post_install.log 2>&1
echo "deb https://dl.google.com/linux/chrome/deb/ stable main" | sudo tee /etc/apt/sources.list.d/google-chrome.list >> post_install.log 2>&1
_success "OK"

echo -n "Adding/Updating Oracle Java APT repository... "
sudo add-apt-repository -y "ppa:webupd8team/java" >> post_install.log 2>&1 &
spinner $!
_success "OK"

echo -n "Adding/Updating Plank APT repository... "
sudo add-apt-repository -y "ppa:ricotz/docky" >> post_install.log 2>&1 &
spinner $!
_success "OK"

echo -n "Adding/Updating PHP 5.6 APT repository... "
sudo add-apt-repository -y "ppa:ondrej/php5-5.6" >> post_install.log 2>&1 &
spinner $!
_success "OK"

echo -n "Adding/Updating Sublime Text 3 PPA... "
sudo add-apt-repository -y "ppa:webupd8team/sublime-text-3" >> post_install.log 2>&1 &
spinner $!
_success "OK"

echo -n "Adding/Updating Touchpad Indicator PPA... "
sudo add-apt-repository -y "ppa:atareao/atareao" >> post_install.log 2>&1 &
spinner $!
_success "OK"

echo -n "Adding/Updating NodeJS PPA... "
sudo add-apt-repository -y "ppa:chris-lea/node.js" >> post_install.log 2>&1 &
spinner $!
_success "OK"

echo -n "Adding/Updating FishShell PPA... "
sudo add-apt-repository -y "ppa:fish-shell/release-2" >> post_install.log 2>&1 &
spinner $!
_success "OK"

echo -n "Adding/Updating Numix Theme PPA... "
sudo add-apt-repository -y "ppa:numix/ppa" >> post_install.log 2>&1 &
spinner $!
_success "OK"

# Update sources
echo -n "Updating Sources... "
sudo apt-get -qq -y update >> post_install.log 2>&1 &
spinner $!
_success "OK"

# Accept future Oracle installation without asking user
if ! commandExists "java"; then
    echo -n "Pre-Accepting future Oracle installation license... "
    echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
    echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
    _success "OK"
fi

# Set mysql password
echo -n "Pre-Configuring MySQL Root password... "
echo mysql-server mysql-server/root_password password root | sudo debconf-set-selections
echo mysql-server mysql-server/root_password_again password root | sudo debconf-set-selections
_success "OK"

# Install softwares
installPackage "curl"
installPackage "dtrx"
installPackage "git"
installPackage "guake"
installPackage "plank"
installPackage "php" "php5 php5-json php5-xdebug php5-intl php5-mysql php5-curl php5-gd php5-mcrypt"
installPackage "google-chrome" "google-chrome-stable"
installPackage "java" "oracle-java7-installer"
installPackage "mysqld" "mysql-server"
installPackage "/opt/extras.ubuntu.com/touchpad-indicator/bin/touchpad-indicator" "touchpad-indicator"
installPackage "node" "nodejs"
installPackage "subl" "sublime-text-installer"
installPackage "fish"
installPackage "cola" "git-cola"
installPackage "numix" "numix-gtk-theme numix-icon-theme"

# Installing LastPass
if [[ ! -f "/usr/lib/mozilla/plugins/libnplastpass64.so" ]]; then
    echo -n "Downloading LastPass... "
    download "https://lastpass.com/lplinux.tar.bz2"
    echo ""
    echo -n "Installing LastPass... "
    (cd "/tmp" && dtrx --one=rename -n "/tmp/lplinux.tar.bz2" && cd lplinux && ./install_lastpass.sh)
    _success "OK"
    echo ""
fi

# Configure GIT
echo -n "Configuring GIT user... "
git config --global user.email "thierry@byscripts.info"
git config --global user.name "Thierry Goettelmann"
_success "OK"

# Install composer
if ! commandExists "composer"; then
    echo -n "Downloading Composer and creating bin symlink... "
    wget -P "$HOME/Development/Php" https://getcomposer.org/composer.phar >> post_install.log 2>&1 &
    spinner $!
    sudo ln -s "$HOME/Development/Php/composer.phar" /usr/local/bin/composer
    sudo chmod +x /usr/local/bin/composer
    _success "OK"
fi

# Install Boris (Php REPL)
if ! commandExists "boris"; then
    echo -n "Installing Boris (Php REPL) via composer... "
    composer global require "d11wtq/boris" >> post_install.log 2>&1 &
    spinner $!
    _success "OK"
fi

# Install Fish Shell config
if test ! -d "$HOME/.config/fish"; then
    echo -n "Cloning Fish Shell config from GIT... "
    git clone https://github.com/ByScripts/fish-config.git "$HOME/.config/fish" >> post_install.log 2>&1 &
    spinner $!
    (cd "$HOME/.config/fish" && git remote set-url origin git@github.com:ByScripts/fish-config.git)
    _success "OK"
fi

# Set Fish as default shell
echo -n "Set Fish Shell as default shell... "
sudo chsh -s /usr/bin/fish "$(whoami)"
_success "OK"

# Download wallpapers
echo -n "Download and apply Batman Wallpapers... "
wget -q -P "$HOME/Images" "https://dl.dropboxusercontent.com/u/9594979/wallpaper-batman.jpg" >> post_install.log 2>&1
wget -q -P "$HOME/Images" "https://dl.dropboxusercontent.com/u/9594979/wallpaper-batman-lock.jpg" >> post_install.log 2>&1
gsettings set org.gnome.desktop.background picture-uri "file:///$HOME/Images/wallpaper-batman.jpg" >> post_install.log 2>&1
gsettings set org.gnome.desktop.background picture-options "centered"
gsettings set org.gnome.desktop.screensaver picture-uri "file:///$HOME/Images/wallpaper-batman-lock.jpg" >> post_install.log 2>&1
gsettings set org.gnome.desktop.screensaver picture-options "centered"
_success "OK"

# Hide desktop icons
echo -n "Hide desktop icons... "
gsettings set org.gnome.desktop.background show-desktop-icons false
_success "OK"

# Enable Gnome Shell extensions
echo -n "Enable Gnome Shell extensions... "
gsettings set org.gnome.shell enabled-extensions "['alternate-tab@gnome-shell-extensions.gcampax.github.com', 'user-theme@gnome-shell-extensions.gcampax.github.com']"
_success "OK"

# Download Gnome Shell Theme
if test ! -d "$HOME/.themes/copernico"; then
    echo -n "Download and apply Gnome Shell theme... "
    mkdir -p "$HOME/.themes"
    git clone https://Byscripts@bitbucket.org/Byscripts/copernico-gnome-shell-theme.git "$HOME/.themes/copernico" >> post_install.log 2>&1 &
    spinner $!
    gsettings set org.gnome.shell.extensions.user-theme name "copernico"
    _success "OK"
fi

# Apply GTK and Mutter theme
echo -n "Apply GTK, Mutter and Icon Numix theme... "
gsettings set org.gnome.desktop.interface gtk-theme "Numix"
gsettings set org.gnome.desktop.wm.preferences theme "Numix"
gsettings set org.gnome.desktop.interface icon-theme "Numix"
_success "OK"

# Display date next to time
echo -n "Display current date next to clock... "
gsettings set org.gnome.desktop.interface clock-show-date true
_success "OK"

# Enable Global Dark Theme
echo -n "Enable Global Dark Theme... "
mkdir -p "$HOME/.config/gtk-3.0" >> post_install.log 2>&1
echo "[Settings]
gtk-application-prefer-dark-theme=1" > "$HOME/.config/gtk-3.0/settings.ini"
_success "OK"

# Enable Guake and Touchpad indicator autostart
echo -n "Add Guake and Touchpad Indicator to autostart... "
cp /opt/extras.ubuntu.com/touchpad-indicator/share/touchpad-indicator/touchpad-indicator-autostart.desktop $HOME/.config/autostart/
cp /usr/share/applications/guake.desktop $HOME/.config/autostart/
_success "OK"

# Install Dev php.ini
echo -n "Copying dev php.ini... "
if test -f /usr/share/php5/php.ini-development; then
    sudo cp /usr/share/php5/php.ini-development /etc/php5/apache2/php.ini
    _success "OK"
else
    _error "File not found"
fi

# Configure Php.ini timezone
echo -n "Configuring php.ini timezone... "
sudo sed -i "s/;date.timezone.*/date.timezone = Europe\/Paris/g" /etc/php5/apache2/php.ini
_success "OK"

# Configure Php.ini Xdebug
echo -n "Configuring php.ini xdebug... "
echo "xdebug.max_nesting_level = 250" | sudo tee -a /etc/php5/apache2/php.ini >> post_install.log 2>&1
_success "OK"

# Create php.ini symlinks
echo -n "Create Php.ini symlinks... "
fish -c php-symlink >> post_install.log 2>&1
_success "OK"

if ! commandExists bower; then
    # Install Bower
    echo -n "Installing Bower... "
    sudo npm install -g bower >> post_install.log 2>&1
    _success "OK"
fi

if ! commandExists gulp; then
    # Install Gulp
    echo -n "Installing Gulp... "
    sudo npm install -g gulp >> post_install.log 2>&1
    _success "OK"
fi

if ! commandExists browserify; then
    # Install Browserify
    echo -n "Installing Browserify... "
    sudo npm install -g browserify >> post_install.log 2>&1
    _success "OK"
fi

if ! commandExists meteor; then
    # Install Meteor
    echo -n "Installing Meteor... "
    curl https://install.meteor.com/  | sh >> post_install.log 2>&1
    _success "OK"
fi

# Install Sublime Text 3 config
if test ! -d "$HOME/.config/sublime-text-3"; then
    echo -n "Cloning Sublime Text 3 config and packages from GIT... "
    git clone https://github.com/ByScripts/sublime-config.git "$HOME/.config/sublime-text-3" >> post_install.log 2>&1 &
    spinner $!
    _success "OK"
fi

if test -n "$phpstormUrl"; then
    fish -c phpstorm-update "$phpstormUrl"
fi

if test -n "$webstormUrl"; then
    fish -c webstorm-update "$webstormUrl"
fi

if test -n "$mongochefUrl"; then
    fish -c Mongochef-update "$mongochefUrl"
fi

if test ! -f "$HOME/Development/PhpStormBaseSettings.jar"; then
    # Get default PhpStorm config
    echo -n "Downloading PhpStorm default configuration... "
    wget -q -P "$HOME/Development" https://dl.dropboxusercontent.com/u/9594979/PhpStormBaseSettings.jar
    _success "OK"
fi

# Configure NPM package destination and add bin folder to path
if test ! -f "$HOME/.npmrc"; then
    echo "prefix = $HOME/.local/node_modules" | tee "$HOME/.npmrc"
    fish -c add_to_path "$HOME/.local/node_modules/bin"
fi