#!/bin/sh
# Script de instalación de entorno
set -e
PSQL_VERSION='10'
VIRTUAL_ENV_FOLDER="$HOME/.virtualenvs"
ROI_PATH="$HOME/roi"
DEV_PATH="$ROI_PATH/desarrollo"
LIBS_PATH="$ROI_PATH/libs"
WEBS_PATH="$ROI_PATH/webs"
PACKAGES_UBUNTU="postgresql-$PSQL_VERSION \
                 postgresql-client-$PSQL_VERSION\
                 postgresql-common \
                 postgresql-client-common \
                 postgresql-contrib-$PSQL_VERSION \
                 postgresql-server-dev-$PSQL_VERSION\
                 postgresql-server-dev-all \
                 libmysqlclient-dev \
                 libxslt1-dev \
                 nodejs \
                 vim \
                 python-virtualenv \
                 python-dev \
                 uwsgi \
                 uwsgi-core \
                 uwsgi-plugin-python \
                 keychain \
                 redis-server \
                 redis-tools \
                 kdiff3 \
                 git"

LIBS="bookcore_client \
      cms_apps \
      cms_engine \
      comments_engine \
      contact_engine \
      dynamic_templates \
      hotel_engine \
      komponist \
      medone \
      meetingroom_engine \
      newsletter_engine \
      shared_engine \
      webmobile"

POSTGRES_HBA="/etc/postgresql/$PSQL_VERSION/main/pg_hba.conf"

# Paso 1. Creación de directorios y ficheros básicos
echo '[+] Configurado environment'
## Paso 1.1 Directorio de virtualenvs
if [ ! -d "$VIRTUAL_ENV_FOLDER" ]; then
    mkdir -p "$VIRTUAL_ENV_FOLDER"
fi
## Paso 1.2 Directorios roi
if [ ! -d "$LIBS_PATH" ]; then
    mkdir -p "$LIBS_PATH"
fi
if [ ! -d "$WEBS_PATH" ]; then
    mkdir -p "$WEBS_PATH"
fi
## Paso 1.3 Instalación del roibackrc
### Existe línea en .bashrc?
if  ! grep -q "source ~/.roibackrc" $HOME/.bashrc; then
    echo "source ~/.roibackrc" >> $HOME/.bashrc
    cat << EOF > $HOME/.roibackrc
VIRTUAL_ENVS_BASE='$VIRTUAL_ENV_FOLDER'
ROIBACK_PATH='$LIBS_PATH'
source $ROI_PATH/desarrollo/entorno.bash
EOF
fi
## Paso 1.4 Instalación de clave SSH
#### Añadimos agente de Keychain
if [ -f "$HOME/.ssh/id_ed25519" ]; then
    CLAVE_SSH="id_ed25519"
elif [ -f "$HOME/.ssh/id_ecdsa" ]; then
    CLAVE_SSH="id_ecdsa"
elif [ -f "$HOME/.ssh/id_rsa" ]; then
    CLAVE_SSH="id_rsa"
else
    echo "[-] CLAVE NO ENCONTRADA"
    exit 1
fi
if ! grep -qP '^eval \$\(keychain.*$' $HOME/.*rc; then

    if ! grep -q "source ~/.${USER}rc" $HOME/.bashrc; then
        echo "source ~/.${USER}rc" >> $HOME/.bashrc
    fi
    cat << EOF > $HOME/.${USER}rc
eval \$(keychain --eval --agents ssh $CLAVE_SSH)
EOF
fi

# Paso 1.5 Añadir fichero hgrc
touch $HOME/.gitignore

if [ ! -f $HOME/.gitconfig ]; then
    read -p "Nombre completo: " NOMBRE_COMPLETO
    read -p "Email: " EMAIL
    cat << EOF > $HOME/.gitconfig
[user]
name = $NOMBRE_COMPLETO
email = $EMAIL

[core]
excludesfile = $ROI_PATH/desarrollo/ignore
editor = vim

[color]
ui = auto

[diff]
tool = vimdiff

[merge]
tool = kdiff3

[merge-tool "kdiff3"]
trustExitCode = false

EOF
fi



# Paso 2. Instalación de paquetes básicos
echo '[+] Agregando repositorio de ppa:git-core/ppa'
sudo add-apt-repository ppa:git-core/ppa -y

DISTRIB_CODENAME=$(cat /etc/lsb-release | grep DISTRIB_CODENAME | awk -F"=" '{print $2}')

if [[ $DISTRIB_CODENAME == "tara" ]]; then
	DISTRIB_CODENAME=bionic
fi

if [[ $DISTRIB_CODENAME == "sylvia" ]]; then
        DISTRIB_CODENAME=xenial
fi

if [ ! -f "/etc/apt/sources.list.d/pgdg.list" ]; then
    echo '[+] Agregando repositorio para postgresql-10'
    echo 'deb http://apt.postgresql.org/pub/repos/apt/ $DISTRIB_CODENAME-pgdg main' | sudo tee -a /etc/apt/sources.list.d/pgdg.list
    wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
fi

echo '[+] Instalando paquetes de sistema'
sudo apt-get update > /dev/null
sudo apt-get install -y $PACKAGES_UBUNTU > /dev/null

# Paso 3. Configuración de PostgreSQL
echo '[+] Configurado PostgreSQL'
## Paso 3.1 Instalación de la extensión hstore
sudo -u postgres psql -d template1 -c "CREATE EXTENSION IF NOT EXISTS hstore;"
## Paso 3.2 Cambio en el pg_hba.conf
sudo -u postgres sed -r -i.bak 's/^(local[ ]+all[ ]+all[ ]+)peer$/\1 md5/g' $POSTGRES_HBA
## Paso 3.3 Reiniciar postgresql
sudo service postgresql restart

# Paso 4. Cambiara permisos /etc/hosts
echo '[+] Configurando /etc/hosts'
sudo chmod 666 /etc/hosts
# Paso 5. Clonado de librerías y/o actualización
echo '[+] Clonando librerías y entorno'
eval $(keychain --eval --agents ssh $CLAVE_SSH)
echo '[+] Instalando librerías'
if [ ! -d $DEV_PATH ]; then
    git clone git@git.roiback.com:entorno/desarrollo $DEV_PATH
fi
for x in $LIBS; do
    if [ ! -d "${LIBS_PATH}/${x}" ]; then
        mkdir -p "${LIBS_PATH}/${x}"
        git clone git@git.roiback.com:libs/${x} "${LIBS_PATH}/${x}"
    fi
done

# Paso 5. Creando enlace simbólico para node
echo '[+] Enlazando node...'
sudo ln -s /usr/bin/nodejs /usr/bin/node
