#! /bin/bash
#License GPL V3
#Author SISalp Dominique.chabord@sisalp.org
#if debug messages divulgate passwords they should not be effective on on-line servers
##-l:	Licence
##-l:	-------
##-l:	#=================================================================
##-l:	# This program is Free Software; you can redistribute it and/or
##-l:	# modify it under the terms of the GNU General Public License
##-l:	# as published by the Free Software Foundation; either version 2
##-l:	# of the License, or (at your option) any later version.
##-l:	#
##-l:	# This program is distributed in the hope that it will be useful,
##-l:	# but WITHOUT ANY WARRANTY; without even the implied warranty of
##-l:	# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##-l:	# GNU General Public License for more details.
##-l:	#
##-l:	# You should have received a copy of the GNU General Public License
##-l:	# along with this program; if not, write to the Free Software
##-l:	# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
##-l:	#
##-l:	#=================================================================
##-l:	# 2022 - today Copyright SISalp www.sisalp.fr
##-l:	# par dominique.chabord@sisalp.org
Version="1.3 14-july-2025"
DownloadSource="http://download.sisalp.net/scripts/populate"
MyName=`basename $0`
#Myself=`realpath $0`
Myself="$MyName"
MyLog="/tmp/$MyName.log"
MyUser=`whoami`
AllParameters="$*"
OptionList="syntax create demo prepare populate welcome save set_models"
DefCountries="fr"
DefLanguage="fr"
DefCreatedDatabase="just_a_new_database"
DefPreparedDatabase="prepared_modules"

#echo "Activation $MyName $AllParameters"
Option="$1"
if [ -z "$Option" ] ; then
	Option="--howto"
fi
shift
case "$Option" in
-h|help|--help)

	topic="$1"
	if [ -z "$topic" ] ; then
		topic="None"
	fi
	case "$topic" in
	None)
		
		echo "Documentation:
--------------

Populate data in a database of a tryton service
Tryton service can be vanilla tryton or a custom edition, depending on its erp_variant parameter value.
"
		for subject in $OptionList ; do
			$Myself --help $subject
			echo "
======================================================================
"
		done
		echo "Logs:
-----
In regular xoe XoeService log
$MyName is quiet on standard output because usually supposed to be run by goe.


-------------------------
Version :	$Version
License :	GPL-V3
Author :	SISalp
Located at :	$Myself
-------------------------
"
		;;
	syntax)
		echo "
Usage:
------
$MyName -h|help|--help	[create[demo|prepare|populate|welcome|save|set_models|syntax]	print this help and exit
$MyName -v|version|--version	print version and exit
$MyName -l|license|--license	print license and exit
$MyName -u|update|--update	update this script
$MyName [-o|howto|--how-to]	print general documentation

$MyName -c|create|--create XoeService [Country] [Database|- DbPassword|-]
$MyName -d|demo|--demo XoeService
$MyName -i|prepare|--prepare XoeService [Country]
$MyName -p[populate|--populate XoeService [Country] [Database|- DbPassword|- [FirstMonth Period \"MyCompany\"]]
$MyName -w|welcome|--welcome XoeService path_to_profile_file
$MyName -sa|save_models|--save_models XoeService
$MyName -se|set_models|--set_models XoeService Country
"
		;;
	create)
		echo "--create
--------------
Create a tryton empty database and create a database reference

Usage of --create option:
--------------

$MyName -c|create|--create XoeService	
$MyName --create XoeService [Country] Database [DbPassword]
with
XoeService :	service name
Country :	[de|es|fr|en]		# en is added, fr is default
Database|- :	database to build, if empty pick a generic name
DbPassword :	admin user password, random password if empty

Main actions with --create option:
-------------
xoe --stop XoeService
xoe --database -createdb $XoeParameters
xoe --start XoeService"
		;;
	demo)
		echo "--demo
--------------
Create a tryton database and fill it with demo data
If erp_variant of the service is tryton, load official tryton project demo data.
If erp_variant is a custom edition name, demo data will be populated according to erp_variant scripts.

Usage of --demo option:
--------------

$MyName --demo XoeService Database DbPassword|-
with
XoeService :	service name

Main actions with --demo option:
--------------
xoe --stop XoeService
xoe --database -createdb XoeService Database
run tryton_demo.py or erp_variant_demo.py
save demo database
xoe --database -save -now XoeService Database
if empty create a demo reference
xoe --database -set -reference XoeService Database
xoe --start XoeService"
		;;
	prepare)
		echo "--prepare
--------------
Create a tryton database and pre-activate a set of basic french modules to create a database reference model
The database model will suit fast population requirements later.
This prepared database can then be archived as reference_pre_activate_modules_fr.sql.gz in /home/sisalpuser/xoe.packages/database_models/erp_variant/x.x/populator/references
erp_variant is either tryton or a custom edition name.
This command is supposed to be executed once per new Tryton release to set up references

Usage of --prepare option:
--------------

$MyName --prepare XoeService Country
with
XoeService :	service name
Country : be|fr|syscohada

Main actions with --prepare option:
--------------
xoe --stop XoeService
xoe --database -createdb XoeService Database
preactivate modules with trytond-admin
load countries, postal codes and currencies with tryton scripts of the service
xoe --database -save -now XoeService Database
if empty xoe --database -set -reference XoeService Database
and move reference_Database.sql.gz to reference_prepared_modules_fr.sql.gz
xoe --start XoeService"
		;;
	populate)
		echo "--populate
--------------
Complement a pre-referenced tryton database fill it with customer's profile data by proteus
The original database was created by --prepare option
If erp_variant of the service is tryton, load tryton predefined data.
If erp_variant is a custom edition name, data will be populated according to erp_variant scripts.
If data origin or populator script tagged with service role are available, they are used instead
and populated database is tagged too with a -'role_name' postfix

Usage of --populate option:
--------------

$MyName -p|populate|--populate XoeService [Country] [Database|- DbPassword|- [FirstMonth Period \"MyCompany\"]]
with
XoeService :	service name
Country :	be|fr|syscohada|en		#fr is default, en is english only and minimal accounting
Database|- :	database to populate
		if Database and following parameters are omitted, a generic example reference is created
DbPassword|- :	admin user password or random password
FirstMonth :	first month of fiscal year 1 - 12, default is 1
Period :	fiscal period duration in months 1|3, default is 1
MyCompany :	\"Company Name\", default is \"Ma Societe\"

Main actions with --populate option:
-------------
xoe --stop XoeService
restore pre-activated refererence reference_pre_activate_modules_fr.sql.gz
/usr/local/bin/xoe --database -restore -force XoeService Database reference_pre_activate_modules_fr.sql.gz
populate data
run populate_fr.py Database FirstMonth Period MyCompany	
save populated database
if empty, /usr/local/bin/xoe --database -save -now XoeService Database
and create a generic reference									
/usr/local/bin/xoe --start XoeService"
		;;
	welcome)
		echo "--welcome
--------------
Similar to --populate but parameters are provides by the calling script
Complement a pre-referenced tryton database fill it with customer's profile data by proteus
The original database was created by --prepare option
If erp_variant of the service is tryton, load tryton predefined data.
If erp_variant is a custom edition name, data will be populated according to erp_variant scripts.
If data origin or populator script tagged with service role are available, they are used instead
and populated database is tagged too with a -'role_name' postfix

Usage of --welcome option:
--------------

$MyName -w|welcome|--welcome XoeService path_to_profile_file
with
XoeService :	service name
path_to_profile_file : profile file format contains values for FirstMonth Period \"MyCompany\", and other custom parameters
in this file, parameters are encode this way:
#profile:	parameter=\\\"value\\\"

Main actions with --welcome option:
-------------
xoe --stop XoeService
restore pre-activated refererence reference_pre_activate_modules_fr.sql.gz
/usr/local/bin/xoe --database -restore -force XoeService Database reference_pre_activate_modules_fr.sql.gz
populate data
run populate_fr.py Database FirstMonth Period MyCompany	
save populated database
if empty, /usr/local/bin/xoe --database -save -now XoeService Database
and create a generic reference									
/usr/local/bin/xoe --start XoeService"
		;;
	save_models)
		echo "--save_models
--------------
Move basic database models created for a service to shared database_models repository

Usage of --save_models option:
--------------

$MyName -sa|save_models|--save_models XoeService
with
XoeService :	service name

Main actions with --save_models option:
-------------
find generic service local references 
move references to database_model"
		;;
	set_models)
		echo "--set_models
--------------
Generate basic database models for a service with a single command

Usage of --set_models option:
--------------

$MyName -se|set_models|--set_models XoeService Country
with
XoeService :	service name
Country :	be|fr|syscohada|-		#fr is default, - is english only and minimal accounting

Main actions with --set_models option:
-------------
$MyName --demo XoeService
$MyName --prepare XoeService Country
$MyName --populate XoeService Country"
		;;
	*)
		echo "no documentation on topic $topic"
		;;
	esac
	exit 0
	;;
-o|howto|--howto)
	echo "setup xoe references for a tryton VDS"
	echo "---------------------------------------------"
	echo ""

	echo "$MyName command can build a full set of pre-populated references of databases for Tryton."
	echo ""
	echo "Get a trytond server fully installed here called XoeService"
	echo ""
	echo "Then the short answer is:"
	echo "$MyName --set_models XoeService Country"
	echo ""
	echo "References are created in database_models/XoeService and you may want to generalize their use"
	echo "by moving them to database_models/tryton/version/ directory"
	echo ""
	echo "If you prefer creating references step by step, please read directions below."
	echo "You can get more about other capabilities of $MyName"
	echo "by $MyName --help"
	echo ""
	echo ""
	echo "1 Generate a reference of a demo database"
	echo "-----------------------------------------"
	echo ""
	echo "$MyName --demo XoeService"
	echo "The demo_database script uses the official tryton project demo proteus script"
	$Myself --help demo
	echo ""
	echo " Place the generated reference at the right place of database_models"
	echo ""
	echo "---------------------------------------------"
	echo ""
	echo "2 Generate a internal, partially populated reference with pre-loaded modules for french accounting"
	echo "--------------------------------------------------------------------------------------------------"
	echo ""
	echo "$MyName --prepare XoeService"
	echo "This unpopulated reference will be used to create a generic example and custom welcome databases for new users"
	echo ""
	$Myself --help prepare
	echo ""
	echo " Now you can run populate_fr.script and it will re-use this reference to speed up database population"
	echo ""
	echo ""
	echo "---------------------------------------------"
	echo ""
	echo "3 Generate a generic reference exemple for new services"
	echo "-------------------------------------------------------"
	echo ""
	echo "$MyName --populate XoeService"
	echo "The populate_fr.script with minimal arguments will generate a reference which can be duplicated to all new services"
	echo "This generation is fast because it uses the reference created by pre_activate_modules_fr.script"
	$Myself --help populate
	echo ""
	echo " Place the generated reference at the right place of database_models"
	echo ""
	echo "---------------------------------------------"
	echo ""
	echo "4 Generate ready to use 'welcome' databases for new users"
	echo "---------------------------------------------------------"
	echo ""
	echo "$MyName --populate XoeService Database|- DbPassword|- FirstMonth Period \"MyCompany\""
	echo "The populate_fr.script can be invoked by goe, using a profile my_company.script generated by the company/societe button"
	echo "my_company.script is a short script which call populate_fr.script with custom parameter values"
	echo "When all arguments are set, populate_fr.script does not care about generic reference generation"
	echo ""
	echo "---------------------------------------------"
	echo ""
	echo "5 Customize ready to use 'welcome' databases for new users"
	echo "---------------------------------------------------------"
	echo ""
	echo "The populate_fr.script can adapt data imported in welcome database to service role"
	echo "It checks if pre-activated data or populator python script exist with the service role tagged in their name"
	echo "For example populate_fr-production.py will be preferred to  populate_fr.py if service role is production"
	echo "In this case, the generic reference generated at step 3 is also tagged with -production in its name."
	echo ""
	echo ""
	echo "---------------------------------------------"
	echo ""
	echo "6 Create an empty database"
	echo "---------------------------------------------------------"
	echo ""
	echo "This script can also create an empty database"
	$Myself --help create
	echo ""
	echo "---------------------------------------------"
	exit 0
	;;
-v|version|--version)
	echo "Version :	$Version"
	exit 0
	;;
-l|license|--license)
	cat $0 | grep "^##-l:" | cut -d: -f2-
	exit 0
	;;
-u|update|--update)
	case "$MyUser" in
	root)
		OldVersion=`$0 --version`
		cd /usr/local/bin
		mv $0 $0.old
		if wget -q $DownloadSource ; then
			chmod 755 $0
			diff $0.old $0
			rm $0.old
			NewVersion=`$0 --version`
			case "$NewVersion" in
			$OldVersion)
				echo "$0 is uptodate $NewVersion"
				;;
			*)
				echo "$0 downloaded new version from $DownloadSource"
				;;
			esac
		else
			echo "cannot download new version of $0 from $DownloadSource"
			rm $0
			mv $0.old $0
		fi
		exit 0
		;;
	*)
		echo "$0 update: You must get administration priviledges root to succeed, please consider sudo"
		exit 1
		;;
	esac
	;;
-c|create|--create|-d|demo|--demo|-i|prepare|--prepare|-p|populate|--populate|-w|welcome|--welcome|-se|set_models|--set_models|-sa|save_models|--save_models)
	;;
*)
	echo "this option $Option is not supported by $Myname"
	$Myself --help syntax
	exit 1
esac

#-------------------------------------------------------------------------
GET_SERVICE_NAME ()
#-------------------------------------------------------------------------
{
XoeService="$1"
if [ -z "$XoeService" ] ; then
	echo "$MyName|$LINENO|$Option|ERROR: 	Parameter XoeService is mandatory with option $Option"
	$Myself --help syntax
	exit 1
fi
if [ ! -d /home/sisalpuser/xoe.services/$XoeService ] ; then
	echo "$MyName|$LINENO|$Option|ERROR: 	Directory of service $XoeService is not found"
	exit 1
fi
variant=`/usr/local/bin/xoe --service -erp_variant -noblabla $XoeService`
version=`/usr/local/bin/xoe --service -version -noblabla $XoeService`
if [ -d /home/sisalpuser/xoe.packages/database_models.$variant/$version ] ; then
	ReferenceDir="/home/sisalpuser/xoe.packages/database_models.$variant/$version"
else
	ReferenceDir="/home/sisalpuser/xoe.packages/database_models/$variant/$version"
fi
ServiceReferencesDir="/home/sisalpuser/xoe.services/$XoeService/references/$variant/$version"
}
#-------------------------------------------------------------------------
COUNTRY ()
#-------------------------------------------------------------------------
{
	Country="$1"
	case "$Country" in
	be)
		Language="fr"
		Accounting="comptabilite"
		;;
	de)
		Language="de"
		Accounting="accounting"
		;;
	es)
		Language="es"
		Accounting="accounting"
		;;
	fr)
		Language="fr"
		Accounting="comptabilite"
		;;
	syscohada)
		Language="fr"
		Accounting="comptabilite"
		;;
	en|-)
		Language=""
		Accounting="accounting"
		;;
	*)
		Language=""
		Accounting="accounting"
		;;
	esac
}
#-------------------------------------------------------------------------
GET_PROFILE ()
#-------------------------------------------------------------------------
{
	if [ ! -z "$1" ] && [ -f $1 ] ; then
		cat $* | grep "^#profile:" | cut -d: -f2- > /tmp/populate_profile_values_`basename $1`_$$.script
		chmod 700 /tmp/populate_profile_values_`basename $1`_$$.script
		. /tmp/populate_profile_values_`basename $1`_$$.script
		cat /tmp/populate_profile_values_`basename $1`_$$.script
		#rm /tmp/populate_profile_values_`basename $1`_$$.script
	else
		case "$1" in
		fr|be|syscohada|en)
			Country="$1"
			shift
			;;
		*)
			Country="fr"
			;;
		esac
		FirstMonth="$1"
		shift
		Period="$1"
		shift
		MyCompany="$*"
		shift
	fi
	if [ -z "$Country" ] ; then Country="fr" ; fi
	if [ -z "$FirstMonth" ] ; then FirstMonth="1" ; fi
	if [ -z "$Period" ] ; then Period="1" ; fi
	if [ -z "$MyCompany" ] ; then MyCompany="Ma Société" ; fi
}
#-------------------------------------------------------------------------
GET_DATABASE ()
#-------------------------------------------------------------------------
{
	case "$Database" in
	-)
		DemoDatabase=`FORMAT_ASCII $XoeService-demo-$version`
		PreparedDatabase=`FORMAT_ASCII $XoeService-$DefPreparedDatabase-$Country-$version`
		PopulateDatabase=`FORMAT_ASCII $XoeService-$Accounting-$Country-$version`
		echo "$LINENO XoeService $XoeService Database $Database"
		MakeReference="yes"
		;;
	*)
		DemoDatabase=`FORMAT_ASCII $Database`
		PreparedDatabase=`FORMAT_ASCII $Database`
		PopulateDatabase=`FORMAT_ASCII $Database`
		MakeReference="no"
		;;
	esac
}
#-------------------------------------------------------------------------
CHOOSE_PREPARED_REFERENCE ()
#-------------------------------------------------------------------------
{
	PreparedReference="None"
	ref_version=`FORMAT_ASCII $version`
	for reference in $ServiceReferencesDir/$XoeService-$DefPreparedDatabase-$Country-$ref_version-$XoeServiceRole.sql.gz $ReferenceDir/populator/references/reference-$DefPreparedDatabase-$Country-$ref_version-$XoeServiceRole.sql.gz $ServiceReferencesDir/$XoeService-$DefPreparedDatabase-$Country-$ref_version.sql.gz $ReferenceDir/populator/references/reference-$DefPreparedDatabase-$Country-$ref_version.sql.gz $ReferenceDir/populator/references/reference_$DefPreparedDatabase-$Country-$ref_version.sql.gz ; do
		if [ -f $reference ] ; then
			PreparedReference="$reference"
			break
		else
			echo "$reference doesn't exist"
		fi
	done
	case "$PreparedReference" in
	None)
		echo "Reference $PreparedReference is not found, building one now"
		$Myself --prepare $XoeService
		PreparedReference="$ReferenceDir/populator/references/reference-$DefPreparedDatabase-$Country-$ref_version.sql.gz"
		;;
	*)
		echo "Reference is $PreparedReference"
		;;
	esac
}
#-------------------------------------------------------------------------
CHOOSE_DEMO_SCRIPT ()
#-------------------------------------------------------------------------
{
	PythonScript="$ReferenceDir/populator/${variant}_demo_$version"
	for good_script in $PythonScript $PythonScript.py ; do
		if [ -e $good_script ] ; then
			break
		fi
	done
	if [ ! -e $PythonScript ] ; then
		echo "$MyName|$LINENO|$Option|ERROR: 	Python script $PythonScript is not found"
		exit 1
	fi
}
#-------------------------------------------------------------------------
CHOOSE_PYTHON_SCRIPT ()
#-------------------------------------------------------------------------
{
	PythonScript="$ReferenceDir/populator/populate_fr_$version"
	for good_script in $PythonScript.$XoeServiceRole $PythonScript.$XoeServiceRole.py $PythonScript $PythonScript.py ; do
		if [ -e $good_script ] ; then
			break
		fi
	done
	case "$good_script" in
	$PythonScript.$XoeServiceRole*)
		XoeReference="comptabilite_fr-$version-$XoeServiceRole.sql.gz"
		;;
	*)
		XoeReference="comptabilite_fr-$version.sql.gz"
		;;
	esac
	PythonScript="$good_script"
	if [ ! -e $PythonScript ] ; then
		echo "ERROR: 	Python script $PythonScript is not found"
		exit 1
	fi
}
#-------------------------------------------------------------------------
EXECUTE ()
#-------------------------------------------------------------------------
{
	echo "`date` $MyName|$LINENO|$Option|EXECUTE $*"
	/usr/local/bin/xoe --log -message $XoeService "$MyName|$LINENO|$MyUser|$Option| $*"
	$*
	echo "`date` $MyName|$LINENO|$Option|EXECUTE  $* done"
}
#-------------------------------------------------------------------------
FORMAT_ASCII ()
#-------------------------------------------------------------------------
{
	#MESSAGE -d "$LINENO FORMAT_ASCII $*"
	# punct ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~. 
	fdn_name=`echo "$*" | iconv -f utf-8 -t US-ASCII//TRANSLIT | tr '[:upper:]' '[:lower:]' | tr '-' 'A' | tr '[:punct:]' '_' | tr 'A' '-' | tr ' ' '_'`
	echo "$fdn_name"
}
#-------------------------------------------------------------------------
STOP ()
#-------------------------------------------------------------------------
{
ToRestart=`xoe --watch -up-noblabla $XoeService`
case "$ToRestart" in
RUNNING)
	#stop service
	/usr/local/bin/xoe --config -set -manual $XoeService
	/usr/local/bin/xoe --stop $XoeService
	;;
esac
#done
}
#-------------------------------------------------------------------------
START ()
#-------------------------------------------------------------------------
{
case "$ToRestart" in
RUNNING)
	#start service
	echo "`date` $LINENO|  /usr/local/bin/xoe --start $XoeService"
	/usr/local/bin/xoe --start $XoeService
	#set service to auto
	echo "`date` $LINENO| /usr/local/bin/xoe --config -set -auto $XoeService"
	/usr/local/bin/xoe --config -set -auto $XoeService
	;;
esac
#done
}
#-------------------------------------------------------------------------
MAKE_REFERENCE ()
#-------------------------------------------------------------------------
{
echo "`date` populate|$LINENO|$Option|MAKE_REFERENCE $*"
if [ -z "$1" ] ; then
	echo "`date` $LINENO| Error: parameter target_reference is empty"
	return 1
fi
origin_database="$1"
shift
target_reference="$1"
target_directory=`dirname $target_reference`

case "$MakeReference" in
yes)
	#save database
	echo "`date` $LINENO| /usr/local/bin/xoe --database -save -now $XoeService $origin_database"
	/usr/local/bin/xoe --database -save -now $XoeService $origin_database
	#create a reference
	/usr/local/bin/xoe --database -set -reference $XoeService $origin_database
	#hide reference in script directory
	if [ ! -d $target_directory ] ; then mkdir --parent $target_directory ; fi
	rm -f $target_reference
	mv $ServiceReferencesDir/reference_$origin_database.sql.gz $target_reference
	/usr/local/bin/xoe --log -message $XoeService "$MyName|$LINENO| $origin_database database is now referenced as $target_reference"
	echo "$origin_database database is now referenced as $target_reference"
	;;
esac
#done
}
#-------------------------------------------------------------------------
BEST_SCRIPT ()
#-------------------------------------------------------------------------
{
	if [ -f  $1 ] ; then
		echo "$1"
	else
		shift
		shift
		echo "$*"
	fi
}
#-------------------------------------------------------------------------
INITIALIZE_MODULES ()
#-------------------------------------------------------------------------
{
	case "$version" in
	5.*)
		EXECUTE $EnvDir/trytond-admin --config $TrytonConf --database $PreparedDatabase --update account_fr account_invoice account_payment account_statement company party product purchase sale stock --activate-dependencies
		ImportPostalCodes=`BEST_SCRIPT $EnvDir/trytond_import_zip : $EnvPython $ModulesDir/country/scripts/import_zip.py`
		EXECUTE $ImportPostalCodes --config $TrytonConf --database $PreparedDatabase
		;;
	6.*|7.*)

		EXECUTE $EnvDir/trytond-admin --config $TrytonConf --database $PreparedDatabase --update account_fr account_invoice account_payment account_statement company party party_avatar product purchase sale stock --activate-dependencies

		ImportCountries=`BEST_SCRIPT $EnvDir/trytond_import_countries : $EnvPython $ModulesDir/country/scripts/import_countries.py`
		ImportCurrencies=`BEST_SCRIPT $EnvDir/trytond_import_currencies : $EnvPython $ModulesDir/currency/scripts/import_currencies.py`
		ImportPostalCodes=`BEST_SCRIPT $EnvDir/trytond_import_postal_codes : $EnvPython $ModulesDir/country/scripts/import_postal_codes.py`

		EXECUTE $ImportCountries --config $TrytonConf --database $PreparedDatabase
		EXECUTE $ImportCurrencies --config $TrytonConf --database $PreparedDatabase
		EXECUTE $ImportPostalCodes --config $TrytonConf --database $PreparedDatabase fr
		;;
	esac
}
#-------------------------------------------------------------------------
APPLY_PROFILE ()
#-------------------------------------------------------------------------
{
	CHOOSE_PREPARED_REFERENCE
	CHOOSE_PYTHON_SCRIPT
	echo "$MyName|$LINENO| $XoeService $PopulateDatabase  Estimated time to full accounting setup  1 mn"
#restore prepared refererence
	EXECUTE /usr/local/bin/xoe --database -restore -force $XoeService $PopulateDatabase $PreparedReference
#populate data
	CompanyName=`FORMAT_ASCII $MyCompany`
	EXECUTE $EnvPython $PythonScript -c $TrytonConf -d $PopulateDatabase -M $FirstMonth -P $Period -C $CompanyName
	echo "`date` $MyName $XoeService $PopulateDatabase xxxxxxxxxxxx $MyCompany $FirstMonth $Period ... : done"
	/usr/local/bin/xoe --log -message $XoeService "$MyName|$LINENO| $PopulateDatabase database is now populated with custom data"
}
#-------------------------------------------------------------------------
#================================================================================
GET_SERVICE_NAME $*
shift
Country="$1"
case "$Country" in
fr|be)
	shift
	;;
*)
	Country="fr"
	;;
esac
Database="$1"
if [ -z "$Database" ] ; then
	Database="-"
else
	Database=`FORMAT_ASCII $1`
	shift
	echo "$MyName|$LINENO|$Option| XoeService $XoeService Database $Database"
fi
DbPassword="$1"
if [ -z "$DbPassword" ] ; then
	DbPassword="-"
else
	shift
fi

#$MyName -c|create|--create XoeService [Country] [Database|- DbPassword|-]
#$MyName -d|demo|--demo XoeService
#$MyName -i|prepare|--prepare XoeService [Country]
#$MyName -p[populate|--populate XoeService [Country] [Database|- DbPassword|- [FirstMonth Period \"MyCompany\"]]
#$MyName -w|welcome|--welcome XoeService path_to_profile_file
#$MyName -s|set_models|--set_models XoeService Country
# --populate $xoe_service $database_name $admin_password 1 1 Ma Societe 

XoeCountries="$*"
/usr/local/bin/xoe --log -message $XoeService "$MyName|$LINENO| call $Myself $AllParameters : Populate a database, version $Version"
EnvDir="/home/sisalpuser/xoe.services/$XoeService/server/bin"
EnvPython="$EnvDir/python"
ModulesDir="/home/sisalpuser/xoe.services/$XoeService/trytond/trytond/modules"
TrytonConf="/home/sisalpuser/xoe.services/$XoeService/config_file/server_$XoeService.conf"
case "$Option" in
-sa|save_models|--save_models)
	cd $ServiceReferencesDir
	for demo in `ls -d $XoeService-demo-*.sql.gz` ; do
		target_file=`echo "$demo" | sed s/^$XoeService-//`
		echo "$MyName|$LINENO|$Option| mv $demo $ReferenceDir/$target_file"
		mv $demo $ReferenceDir/$target_file
	done
	for reference in `ls -d $XoeService-$DefPreparedDatabase-*.sql.gz` ; do
		target_file=`echo "$reference" | sed s/^$XoeService-//`
		echo "$MyName|$LINENO|$Option| mv $reference $ReferenceDir/populator/references/reference-$target_file"
		mv $reference $ReferenceDir/populator/references/reference-$target_file
	done
	
	for populated in `ls -d $XoeService-comptabilite-*.sql.gz` ; do
		target_file=`echo "$populated" | sed s/^$XoeService-//`
		echo "$MyName|$LINENO|$Option| mv $populated $ReferenceDir/$target_file"
		mv $populated $ReferenceDir/$target_file
	done
#	for populated in `ls -d $XoeService-accounting-*.sql.gz` ; do
#		target_file=`echo "$populated" | sed s/^$XoeService-//`
#		echo "$MyName|$LINENO|$Option| mv $populated $ReferenceDir/accounting-$target_file"
#		mv $populated $ReferenceDir/accounting-$target_file
#	done
	exit 0
	;;
-se|set_models|--set_models)

	echo "$MyName|$LINENO|$Option| $MyName --demo $XoeService"
	echo "====================================================================================================="
	$MyName --demo $XoeService
	echo "$MyName|$LINENO|$Option| $MyName --prepare $XoeService fr"
	echo "====================================================================================================="
	$MyName --prepare $XoeService fr
	echo "$MyName|$LINENO|$Option| $MyName --populate $XoeService fr"
	echo "====================================================================================================="
	$MyName --populate $XoeService fr
	echo "$MyName|$LINENO|$Option| $MyName --save_models $XoeService"
	echo "====================================================================================================="
	$MyName --save_models $XoeService
	exit 0
	;;
esac

STOP
case "$Option" in
-c|create|--create)
	COUNTRY $Country
	case "$Database" in
	-)
		Database=`FORMAT_ASCII $XoeService-$DefCreatedDatabase_$Country-$version`
		echo "$MyName|$LINENO|$Option| XoeService $XoeService Database $Database"
		EXECUTE /usr/local/bin/xoe --database -createdb $XoeService $Database $DbPassword en $Language
		;;
	*)
		EXECUTE /usr/local/bin/xoe --database -createdb $XoeService $Database $DbPassword en $Language
		;;
	esac
	;;
-d|demo|--demo)
	CHOOSE_DEMO_SCRIPT
	GET_DATABASE $Database
	EXECUTE $Myself --create $XoeService $DemoDatabase $DbPassword
	echo "$MyName|$LINENO|$Option|Populating $DemoDatabase with demo... Please wait for Ready for connections notification below - Estimated time to full demo setup  15 mn"
	EXECUTE $EnvPython $PythonScript -c $TrytonConf -d $DemoDatabase
	#MAKE_REFERENCE $DemoDatabase $ServiceReferencesDir/demo-$version.sql.gz
	MAKE_REFERENCE $DemoDatabase $ServiceReferencesDir/$DemoDatabase.sql.gz
	/usr/local/bin/xoe --log -message $XoeService "$Myself|$LINENO| $DemoDatabase database is now populated with demo data"
	echo "$Myself --demo $XoeService $DemoDatabase xxxxxxxxxxxx ... : done"
	;;
-i|prepare|--prepare)
	GET_PROFILE $*
	COUNTRY $Country
	GET_DATABASE -
	echo "$MyName|$LINENO|$Option| XoeService $XoeService Database $PreparedDatabase"
	EXECUTE $Myself --create $XoeService $PreparedDatabase $DbPassword
	INITIALIZE_MODULES $PreparedDatabase
	#MAKE_REFERENCE $PreparedDatabase $ReferenceDir/populator/references/reference_$DefPreparedDatabase-$Country-$version.sql.gz

	MAKE_REFERENCE $PreparedDatabase $ServiceReferencesDir/$PreparedDatabase.sql.gz
	echo "$Myself $XoeService $PreparedDatabase xxxxxxxxxxxx $MyCompany $FirstMonth $Period ... : done"
	/usr/local/bin/xoe --log -message $XoeService "$Myself|$LINENO| $PreparedDatabase database reference is now initialized with $Country accounting basic modules unpopulated"
	;;
-p|populate|--populate)
	GET_PROFILE $*
	COUNTRY $Country
	GET_DATABASE $Database
	XoeServiceRole=`xoe --config -get -role $XoeService | cut -f2`
	echo "$MyName|$LINENO|$Option| XoeService $XoeService Database $PopulateDatabase"
	APPLY_PROFILE  $PopulateDatabase
	MAKE_REFERENCE $PopulateDatabase $ServiceReferencesDir/$PopulateDatabase.sql.gz
	;;
-w|welcome|--welcome)
	GET_PROFILE $*
	COUNTRY $Country
	GET_DATABASE $Database
	XoeServiceRole=`xoe --config -get -role $XoeService | cut -f2`
	echo "$MyName|$LINENO|$Option| XoeService $XoeService Database $PopulateDatabase"
	MakeReference="yes"
	APPLY_PROFILE  $PopulateDatabase
	MAKE_REFERENCE $PopulateDatabase $ServiceReferencesDir/$PopulateDatabase.sql.gz
	;;
-sa|save_models|--save_models)
	cd $ServiceReferencesDir
	
	for demo in `ls -d $XoeService-demo-*.sql.gz` ; do
		target_version=`echo "$reference" | cut -d- -f3 | basename ".sql.gz"`
		mv $demo $ReferenceDir/demo-$target_version.sql.gz
	done
	for reference in `ls -d $XoeService-$DefPreparedDatabase-*.sql.gz` ; do
		target_country=`echo "$reference" | cut -d- -f3`
		target_version=`echo "$reference" | cut -d- -f4 | basename ".sql.gz"`
		mv $reference $ReferenceDir/populator/references/reference-$DefPreparedDatabase-$target_country-$target_version.sql.gz
	done
	
	for populated in `ls -d $XoeService-comptabilite-*.sql.gz` ; do
		target_country=`echo "$populated" | cut -d- -f2`
		target_version=`echo "$populated" | cut -d- -f2 | basename ".sql.gz"`
		mv $populated $ReferenceDir/comptabilite-$target_country-$target_version.sql.gz
	done
	for populated in `ls -d $XoeService-accounting-*.sql.gz` ; do
		target_country=`echo "$populated" | cut -d- -f3`
		target_version=`echo "$populated" | cut -d- -f4 | basename ".sql.gz"`
		mv $populated $ReferenceDir/accounting-$target_country-$target_version.sql.gz
	done
	;;


esac
#START
exit 0
