#!/bin/bash

GIT_PROJECT_NAME="gamectrl"

# NEW INSTALL
if [ ! -d $HOME/bin ]; then
    echo "Initialize Ctrl"

    if [ ! -d $HOME/$GIT_PROJECT_NAME ]; then
        cd $HOME; git clone http://git.x-legend.com/it-dev-public/${GIT_PROJECT_NAME}.git
    else
        cd $HOME/$GIT_PROJECT_NAME/
        REMOTE_VERSION=$(git ls-remote http://git.x-legend.com/it-dev-public/${GIT_PROJECT_NAME}.git HEAD | awk -F" " '{print $1}')
        LOCAL_VERSION=$(git rev-parse HEAD)
        if [[ "$REMOTE_VERSION" != "$LOCAL_VERSION" ]]; then
            cd $HOME/$GIT_PROJECT_NAME/; git pull
        else
            echo "Already up-to-date."
        fi
    fi

    if [ ! -d $HOME/www/bin/UPDATES/ ]; then
    	mkdir -p $HOME/www/bin/UPDATES/
    fi

    cd $HOME/$GIT_PROJECT_NAME/bin/
    cp -arf updatectrl $HOME/www/bin/
    cp -arf updatectrl $HOME/www/bin/UPDATES/

    cd $HOME/$GIT_PROJECT_NAME/.git/
    tag=$(git rev-parse --short HEAD) 

    if [ ! -f $HOME/www/bin/UPDATES/Ctrl-${tag}.tar.gz ]; then
        cd $HOME/$GIT_PROJECT_NAME/
        tar cvzf $HOME/www/bin/UPDATES/Ctrl-${tag}.tar.gz .gamerc bin .psqlrc .functions
    fi

    cd $HOME/www/bin/UPDATES/
    sh updatectrl Ctrl-${tag}.tar.gz

# UPDATE
else
    echo "Update Ctrl"

    if [ ! -d $HOME/$GIT_PROJECT_NAME ]; then
        cd $HOME; git clone http://git.x-legend.com/it-dev-public/${GIT_PROJECT_NAME}.git
    else
        if [[ "$1" == "force" ]]; then
            UPDATE_TAG="1"

        else
            cd $HOME/$GIT_PROJECT_NAME/
            REMOTE_VERSION=$(git ls-remote http://git.x-legend.com/it-dev-public/${GIT_PROJECT_NAME}.git HEAD | awk -F" " '{print $1}')
            LOCAL_VERSION=$(git rev-parse HEAD)
            if [[ "$REMOTE_VERSION" != "$LOCAL_VERSION" ]]; then
                UPDATE_TAG="1"
            else
                UPDATE_TAG="0"
            fi
        fi

        if [[ "$UPDATE_TAG" == "1" ]]; then
            cd $HOME/$GIT_PROJECT_NAME/; git pull
        
            if [ ! -d $HOME/www/bin/UPDATES/ ]; then
            	mkdir -p $HOME/www/bin/UPDATES/
            fi

            cd $HOME/$GIT_PROJECT_NAME/bin/
            cp -arf updatectrl $HOME/www/bin/
            cp -arf updatectrl $HOME/www/bin/UPDATES/

            cd $HOME/$GIT_PROJECT_NAME/.git
            tag=$(git rev-parse --short HEAD) 

            if [ ! -f $HOME/www/bin/UPDATES/Ctrl-${tag}.tar.gz ]; then
                cd $HOME/$GIT_PROJECT_NAME/
                tar cvzf $HOME/www/bin/UPDATES/Ctrl-${tag}.tar.gz .gamerc bin .psqlrc .functions
            fi

            cd $HOME/www/bin/UPDATES/
            sh updatectrl Ctrl-${tag}.tar.gz    
        elif [[ "$UPDATE_TAG" == "0" ]]; then
            echo "Already up-to-date."
        fi
    fi
fi