#!/bin/bash

currentScriptPath=$(pwd)

help="${0} : here are all the options (which can be used like this : \"-p\" for \"--path\") and their default value :
${0} --newFilesPath \$HOME/kis/ --ignore photomaton --only photomaton --configurationPath \$HOME/projets/laundries/next-gen/services/configuration --increment 1 --rindex 1"

POSITIONAL=()
while [[ $# -gt 0 ]]
do
key="$1"

case $key in    
    -n|--newFilesPath)
    newFilesPath="$2"
    shift
    shift
    ;;
    -c|--configurationPath)
    configurationPath="$2"
    shift
    shift
    ;;
    -i|--ignore)
    ignore="$2"
    shift
    shift
    ;;
    -o|--only)
    only="$2"
    shift
    shift
    ;;
    -e|--increment)
    increment="$2"
    shift
    shift
    ;;
    -r|--rindex)
    rindex="$2"
    shift
    shift
    ;;
    -h|--help)
    echo "${help}"
    exit 0
    shift
    shift
    ;;
    *)    # unknown option
    POSITIONAL+=("$1") # save it in an array for later
    shift # past argument
    ;;
esac
done

set -- "${POSITIONAL[@]}" # restore positional parameters

if [[ -z $newFilesPath ]] ; then
    echo "Missing newFilesPath "
    echo "${help}"
    exit 0
fi

if [[ -z $configurationPath ]] ; then
    echo "Missing configurationPath "
    echo "${help}"
    exit 0
fi

int_regex='^[+-]?[0-9]+$'
if [[ -z $increment || $increment =~ $int_regex ]] ; then
    increment=1
    echo "Using default increment value : ${increment}"
fi

if [[ -z $rindex || $rindex =~ $int_regex || $rindex -lt 1 ]] ; then
    rindex=1
    echo "Using default rindex value : ${rindex}"
fi

# Always ignore develop and master
ignore="$ignore,develop,master"

echo "Going into $configurationPath"
cd $configurationPath

# take all remote branches but remove path
branches=$(git branch -l -a -q | grep remotes | rev | cut -d'/' -f1 | rev)

function processBranches {
    local branchesArg=${1}
    local ignore=${2}
    local newFilesPath=${3}
    local configurationPath=${4}
    
    local i=0

    previousIFS=$IFS
    IFS=$'\n'

    echo "branches : $branchesArg"
    echo "ingore : $ignore"

    for currentBranch in $branchesArg ; do
        
        # Remove '*' char
        currentBranch=$(echo $currentBranch | sed 's/*//')
        filteredBranch=$(echo $ignore | grep $currentBranch)
        if [[ -n $filteredBranch ]]; then
            echo "Ignore $currentBranch"
            continue
        fi
        
        echo "Processing $currentBranch"
        
        # Checkout branch
        cmd="git checkout -q $currentBranch"
        echo "$cmd"
        eval $cmd

        # Pull branch
        cmd="git pull -q"
        echo "$cmd"
        eval $cmd

        # Copy files
        cmd="cp -f -r \"$newFilesPath\" \"$configurationPath/debian-package/\""
        echo "$cmd"
        eval $cmd

        # Check if there is something to commit
        changes=$(git status -s)
        if [[ -z $changes ]];then
            echo "Nothing to commit, ignoring $currentBranch"
            continue
        fi

        # find correct index
        packageFullVersion=$(cat ./version)
        packageVersion=$(echo $packageFullVersion | cut -d'-' -f1)
        versionName=$(echo $packageFullVersion | cut -d'-' -f2-)

        # Loop through version levels (major, minor...)
        previousIFS=$IFS
        local IFS='.'
        while read -ra sub_version; do

            j=0
            len=${#sub_version[@]}
            for i in "${sub_version[@]}"; do

                aimedIndex=$(expr $len - $rindex)
                # If we found the one we wanted to change
                if [[ $j == $aimedIndex ]]; then
                    # Increment it
                    newVersion=$(expr $i + $increment)
                    sub_version[$j]=$newVersion
                    break
                fi
                
                j=$(expr $j + 1)
            done

            break
        done <<< "$packageVersion"
        
        # Rebuild package line
        packageVersion=${sub_version[*]}
        version="${packageVersion}-${versionName}"
        
        local IFS=$previousIFS

        echo "New $currentBranch version : $version"
        echo -n $version > "./version"

        # Add
        cmd="git add -A"
        echo "$cmd"
        eval $cmd

        # Commit
        cmd="git commit -m \"Automatic config update\""
        echo "$cmd"
        eval $cmd

    done

    IFS=$previousIFS
}

processBranches "$branches" "$ignore" "$newFilesPath" "$configurationPath"

echo "Going back into $currentScriptPath"
cd $currentScriptPath