#!/bin/bash

# Migration vers ScoDoc 8
#
# E. Viennet, dec 2020
#
# Passe l'installation courante de ScoDoc 7 à ScoDoc 8
#  A ce jour, ScoDoc 8 n'est pas recommandé en production !
#
# - l'installation ScoDoc 7 doit être à jour.
# - passe de SVN à GIT: pas de retour en arrière.
# - déplace la config de config/scodoc_config.py 
#    vers /opt/scodoc/var/scodoc/config/scodoc_local.py


source config.sh
source utils.sh

check_uid_root "$0"

scodocctl stop

scodoc7=/opt/ScoDoc7
if [ -e "$scodoc7" ]
then
    echo "/opt/ScoDoc7 already exists. Move or remove it before retrying."
    exit 1;
fi

# 0- Upgrade and check local config
cd "$SCODOC_DIR" || { echo "Fatal error: can't cd to $SCODOC_DIR"; exit 2; }
svn up || { echo "Fatal error: can't apply last svn up"; exit 3; }

local_config_diff=$(svn diff config/scodoc_config.py | wc -l)

# 1- Install git
apt-get update
apt-get update || { echo "apt-get update failed with $?"; exit 4; }
apt-get -y install git

# 2- Download ScoDoc8
printf "\nDownloading files...\n"
cd "$SCODOC_DIR"/.. || { echo "Fatal error: can't cd to $SCODOC_DIR"; exit 2; }

mv ScoDoc "$scodoc7"

git clone https://scodoc.org/git/viennet/ScoDoc.git || { echo "Fatal error: can't clone git repository"; exit 5; }
cd ScoDoc || { echo "Fatal error: can't cd to $SCODOC_DIR"; exit 6; }

git checkout ScoDoc8 || { echo "Fatal error: can't checkout ScoDoc8 branch"; exit 7; }

# 3- Migrate user's configuration if needed
if [ "$local_config_diff" -ne 0 ]
then
    src="$scodoc7"/config/scodoc_config.py
    dst="${SCODOC_VAR_DIR}/config/scodoc_local.py"
    if [ -e "$dst" ]
    then
        echo "Warning: moving ${dst} to ${dst}.old"
        printf "=> vérifiez votre configuration locale avant utilisation.\n\n"
        mv "$dst" "$dst".old
    fi
    echo 
    echo "Copying local configuration file $src"
    echo "to $dst"
    cp  "$src" "$dst"
fi

printf "\nDone.\nPlease start scodoc to use ScoDoc8: systemctl start scodoc\n"
