#!/bin/bash

currentScriptPath=$(pwd)

help="${0} : Will increment configuration version by a selected amount (1 by default) 
here are all the options (which can be used like this : \"-c\" for \"--component\") and their default value :
${0} --group group --team laundry --project revolution --channel prod --basefolder /home/..../dependencies --bypass photomaton,photome-uk (do not increment those distributions) --increment 1 --rindex 1"

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

case $key in 
    -t|--team)
    team="$2"
    shift
    shift
    ;;
    -p|--project)
    project="$2"
    shift
    shift
    ;;
    -g|--group)
    group="$2"
    shift
    shift
    ;;
    -f|--basefolder)
    basefolder="$2"
    shift
    shift
    ;;
    -c|--channel)
    channel="$2"
    shift
    shift
    ;;
    -b|--bypass)
    bypass="$2"
    shift
    shift
    ;;
    -i|--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 $channel ]] ; then
    echo "Missing channel: "
    echo "${help}"
    exit 0
fi

if [[ -z $basefolder ]] ; then
    pwd=$("pwd")
    cd ../../../../../dependencies
    newFolder=$("pwd")
    cd "${pwd}"
    basefolder="${newFolder}"
    echo "Using default basefolder value : ${basefolder}"
fi

if [[ -z $bypass ]] ; then
    bypass=""
    echo "Using default bypass value : ${bypass}"
fi

if [[ -z $distribution ]] ; then
  distribution="photomaton"
  echo "Using default distribution value : ${distribution}"
fi

if [[ -z $team ]] ; then
  team="laundry"
  echo "Using default team value : ${team}"
fi

if [[ -z $project ]] ; then
  project="revolution"
  echo "Using default project value : ${project}"
fi

if [[ -z $group ]] ; then
  group="group"
  echo "Using default group value : ${group}"
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

# FUNCTIONS ===========================================================

function join_by { local d=${1-} f=${2-}; if shift 2; then printf %s "$f" "${@/#/$d}"; fi; }

update_dependencies()
{
    dependencies=$1
    folder=$2

    echo "# Save current configuration"
    tempFile="${folder}/tmp"

    config_line=$(cat ${dependencies} | grep "kis-configuration")

    # Read aptly_dependencies
    while IFS= read -r aptlyline; do

        package=$(echo $aptlyline | cut -d'=' -f1)
        
        # if kis-configuration, replace with new one
        if [[ $package == "kis-configuration" ]]; then
            
            # find correct index
            packagefullversion=$(echo $aptlyline | cut -d'=' -f2)
            packageBranch=$(echo $aptlyline | cut -d'=' -f3-)
            packageVersionName=$(echo $packagefullversion | cut -d'-' -f2-)
            packageVersion=$(echo $packagefullversion | cut -d'-' -f1)
            
            #indexedVersion=$(echo $packageVersion | rev | cut -d'.' -f${rindex} | rev )
            
            # Loop through version levels (major, minor...)
            while IFS='.' 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=$(join_by '.' "${sub_version[@]}")

            aptlyline="${package}=${packageVersion}"
            if [ -n ${packageVersionName} ]; then
                aptlyline="${aptlyline}-${packageVersionName}"
            fi
            aptlyline="${aptlyline}=${packageBranch}"

            echo "# new configuration line : ${aptlyline}"

        fi
        echo "${aptlyline}" >> "${tempFile}"

    done < "${dependencies}"

    echo "removing ${dependencies}"
    rm "${dependencies}"
    mv "${tempFile}" "${dependencies}"
}

# =====================================================================

project_folder="${basefolder}/${group}/${team}/${project}"
echo "Project folder ${project_folder}"

echo "# Process each distribution"

distr_list=$(ls -l "${project_folder}" | grep '^d' | awk -F' ' '{print $NF}')
for current_distr in $distr_list; do

    current_distr_folder="${project_folder}/${current_distr}"

    # Ignore selected distributions
    distr_filter=$(echo ${bypass} | grep ${current_distr})
    if [[ -z $distr_filter ]]; then

        echo "# Processing distribution ${current_distr}"

        channel_folder="${current_distr_folder}/${channel}"
        echo "channel folder ${channel_folder}"

        dependencies_file="${channel_folder}/aptly_dependencies"

        update_dependencies "${dependencies_file}" "${channel_folder}"
    fi

done
