#!/bin/bash

# Database parameters
DB_USER=nuxeo-connect
DB_HOST=localhost
DB_NAME=nuxeo-connect
# Filesystem params
ROOT_PROJECT=/opt/connect/studio/projects
BACK_UP=/opt/studio-projects-backup
# GitLab params
TOKEN=TvVU56dSkyG99JCRjnMT
GITLAB_URL=http://connecttest0.nuxeo.com
GITLAB_SSH=git@connecttest0.nuxeo.com:studio/

# Move to the root of the projects
cd $ROOT_PROJECT

export PGPASSWORD=secret

# Get the list of project id
psql -h $DB_HOST -U $DB_USER -d $DB_NAME \
	-c "select symbolicname from connectproject;" \
	--set ON_ERROR_STOP=on \
	--no-align \
    -t \
    --field-separator ' ' \
    --quiet \
| while read project ; do
if [ -d "$project" ]; then
    echo "Process project : $project ..."
    # Check if folder does not already exist
    if [ ! -d "$BACK_UP/$project" ]; then
        # Move folder to backup directory
        cp -R "$project" "$BACK_UP"
    fi

	# For each project, go to the file system 
    cd "$project"

    # If there are uncommited files, create a commit before migration
    if [ -n "$(git status --porcelain)" ]; then
        git add --all
    	git commit -m "Commit before project migration." --quiet
    fi

    # Create the new folder "studio"
    mkdir studio
    
    # Move all files except ".git" directory
    for file in $(ls -a -I .git -I . -I .. -I studio) ; do
    	mv $file studio
    done

    #############################################
	# Create the settings file application.xml
	#############################################
    projectName=`echo "$project" | sed "s/'/''/g"`
    read targetversion idProject <<< $(psql \
    	-X -h $DB_HOST -U $DB_USER -d $DB_NAME \
    	--single-transaction \
    	--set ON_ERROR_STOP=on \
    	--no-align \
    	-t \
    	--field-separator ' ' \
    	--quiet \
    	-c "select targetversion, sp.id from studio_project sp 
    		inner join connectproject cp
			on cp.id = sp.projectid
			where cp.symbolicname = '$projectName';")

    # Get list of target packages
    declare -a targetpackages=($(psql \
        -X -h $DB_HOST -U $DB_USER -d $DB_NAME \
        --single-transaction \
        --set ON_ERROR_STOP=on \
        --no-align \
        -t \
        --field-separator ' ' \
        --quiet \
        -c "select item from studio_project sp
            inner join sp_packageversions pv
            on pv.id = sp.id
            where sp.id = '$idProject';"))

    echo "<application>" > application.xml
    echo "  <targetVersion>$targetversion</targetVersion>" >> application.xml
    if [ ${#targetpackages[@]} = 0 ]; then 
        echo "  <targetPackagesVersions class=\"empty-list\"/>" >> application.xml
    else 
        echo "  <targetPackagesVersions>" >> application.xml
        # Loop for each target package
        for tp in "${targetpackages[@]}"; do echo "    <string>$tp</string>" >> application.xml; done
        echo "  </targetPackagesVersions>" >> application.xml
    fi
    echo -n "</application>" >> application.xml

	#############################################
	# Create the project on GitLab
	#############################################
    # replace ' with '_'
    projectName=`echo "$project" | tr "'" _`
    curl --header "PRIVATE-TOKEN: $TOKEN" --data "name=$projectName" $GITLAB_URL/api/v3/projects

    # Add the remote in the config of the repo
    # convert the project name to lower case
    projectName=`echo "$projectName" | tr [:upper:] [:lower:]`
    # replace space with '-'
    projectName=`echo "$projectName" | tr " " -`
    remote_url=$GITLAB_SSH
    remote_url+=$projectName
    remote_url+=".git"
	git remote add origin $remote_url

	# Add all modified files and push them on remote
	git add --all .
	git commit --author 'Studio <Studio>' -m "Migrate the project for the branch management." --quiet
	git push origin master --quiet
	
	##########################################################
	# Update the value of the sshUrl in studio_projects table
	##########################################################
	psql -X -h $DB_HOST -U $DB_USER -d $DB_NAME \
		-c "update studio_project set sshurlproject = 'studio/$projectName.git' where id = '$idProject'"

    # Go back to the root of the projects
    cd ..
    # Remove project directory
    rm -fr "$project" 
    fi
done
