#!/bin/bash

set -e
set -v
echo
echo "configuring settings common among OSes"
sudo true

#zsh
if [[ -z $DONT_CHANGE_SHELL ]]; then
    echo "changing shell to zsh"
    chsh -s `which zsh` $USER 
fi

CURL="curl -sSf"

#submodules
DIR=`realpath $DIR`
echo "using $DIR as the top level directory"
cd $DIR
git submodule update --init --recursive

#configs
ln -vfs "$DIR/.vim" ~/.
ln -vfs "$DIR/.vimrc" ~/.
ln -vfs "$DIR/.tmux.conf" ~/.
rm -f "~/.zshrc"
ln -vfs "$DIR/.zshrc" ~/.
ln -vfs "$DIR/.setenv" ~/.
ln -vfs "$DIR/.oh-my-zsh" ~/.
ln -vfs "$DIR/.oh-my-zsh-plugins/zsh-syntax-highlighting" ~/.oh-my-zsh/custom/plugins/
ln -vfs "$DIR/.Slic3r" ~/.
ln -vfs "$DIR/.ghci" ~/.
ln -vfs "$DIR/.conkyrc" ~/.
mkdir -p ~/.kde/share/config/
ln -vfs "$DIR/.kdiff3rc" ~/.kde/share/config/kdiff3rc
ln -vfs "$DIR/.gitconfig.linux.private" ~/.gitconfig
mkdir -p ~/.config/autostart/
# autostart apps
ln -vfs "$DIR/.config/autostart/redshift-gtk.desktop" ~/.config/autostart/
mkdir -p ~/.config/vdirsyncer/
ln -vfs "$DIR/.config/vdirsyncer/config" ~/.config/vdirsyncer/
ln -vfs "$DIR/.config/redshift.conf" ~/.config/redshift.conf

source ~/.setenv

cd "$DIR/.vim/bundle/YouCompleteMe/"
git submodule update --init --recursive
python install.py --clang-completer

# symlink 'nodejs' as node on some systems
# will replace symlink if it exists, but won't replace regular file
if [[ ! -f /usr/bin/node ]]; then
    sudo ln -vfs /usr/bin/nodejs /usr/bin/node
fi

# tools
ln -vfs "$DIR/tools" ~/

# stuff that does not like symbolic links
mkdir -vp ~/.config/terminator
rm -f ~/.config/terminator/config
ln "$DIR/.config/terminator/config" ~/.config/terminator/config

#install fonts
mkdir -p ~/.fonts
cp -rv "$DIR/fonts" ~/.fonts
set +e
fc-cache -rv
sudo fc-cache -rv
set -e

#rust
echo "installing rust"
RUSTUP_TEMP="/tmp/blastoff.sh"
$CURL https://sh.rustup.rs > "$RUSTUP_TEMP"
chmod a+x "$RUSTUP_TEMP"
"$RUSTUP_TEMP" -y
rm -f "$RUSTUP_TEMP"
rustup update
rustup default stable
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
cd "$DIR/../"
echo "getting rust sources..."
if [[ ! -d rust ]]; then
    git clone https://github.com/rust-lang/rust.git
else
    cd rust 
    git pull
fi

set +e
cargo uninstall rustfmt
cargo uninstall racer
set -e
cargo install rustfmt
cargo install racer

# go
export GOPATH="$HOME/go"
mkdir -p "$GOPATH"

# excercism
go get -u github.com/exercism/cli/exercism

# talks: reveal-md
sudo npm install -g reveal-md
sudo npm install -g diff-so-fancy

# vdir syncer
echo "installing vdirsyncer"
sudo pip install vdirsyncer

if [[ -z $USER ]]; then
    USER=`whoami`
fi

# normalize npm permissions
mkdir -p $HOME/.npm
sudo chown $USER $HOME/.npm -R

echo
echo "now go ahead and restart"
echo