#!/usr/bin/env bash

CI_LIB_DIR=/usr/bin/lib
# shellcheck disable=SC1091
source "${CI_LIB_DIR}/xivo-version.sh"
# shellcheck disable=SC1091
source "${CI_LIB_DIR}/dry-run.sh"
# shellcheck disable=SC1091
source "${CI_LIB_DIR}/helpers.sh"

usage() {
    cat <<EOF
Usage: ci-bump-xivo [-h] [--dry-run] <version.subversion>
 - <version.subversion> mandatory, numeric version : 2017.03.02 for instance
 - --dry-run optionnal, does not bump
 - -h, --help, will display this help if passed as first argument.
EOF
}

set_is_lts() {
    version_table=("${!LTS_TABLE[@]}")

    if [[ "${version_table[*]}" =~ ${1} ]]; then
        IS_LTS=true
    else
        if [ "${IS_CURRENT_LTS_RELEASED}" = "true" ]; then
            IS_LTS=true
        else
            IS_LTS=false
        fi
    fi
}

remove_packager() {
    packager_project=$1
    if [[ "$packager_project" = "" || "$packager_project" = "*" || "$packager_project" = "/" ]]; then
        cmn_echo_warn "Can't remove such project : $packager_project"
        exit_abnormally
    fi
    if [[ -e "$packager_project" ]]; then
        cmn_echo_important "Removing packager project $packager_project"
        rm -rf "${packager_project:?}"
    fi
}

assert_not_called_on_root() {
    if [[ "$PWD" = "" || "$PWD" = "*" || "$PWD" = "/" ]]; then
        cmn_echo_warn "You called this script here : $PWD"
        cmn_echo_warn "It is too dangerous to call this script on root folder, exiting"
        exit_abnormally
    fi
}

main() {
    assert_not_called_on_root
    verify_help_asked "$1"
    verify_dry_run "$1"
    if [ "$DRY_RUN" = true ]; then
        shift
    fi
    version="$1"
    shift
    verify_version "${version}"
    major_version=$(echo "${version}" | grep -o '^.\{0,7\}')
    set_lts_codename "${major_version}"
    set_branch "${major_version}"
    set_is_lts "${major_version}"

    if [[ "${version}" = "${major_version}" ]]; then
        numeric_version="${major_version}.00"
    else
        verify_numeric_version "${version}"
        numeric_version=$(echo "${version}" | grep -o '^.\{0,10\}')
    fi

    git clone "git@gitlab.com:xivo.solutions/xivo.git"
    cd xivo || exit
    git pull
    if [ "$DRY_RUN" = true ]; then
        echo_dry_run "would run xivo-bump-package-version ${numeric_version} ${LTS_CODENAME} ${BRANCH} ${IS_LTS}"
        git checkout "${BRANCH}"
        echo_dry_run "Current VERSION $(cat VERSION)"
        echo_dry_run "Current VERSION-LTS $(cat VERSION-LTS)"
        echo_dry_run "Changelog head $(head -1 debian/changelog)"
    else
        xivo-bump-package-version "${numeric_version}" "${LTS_CODENAME}" "${BRANCH}" "${IS_LTS}"
    fi
    cd ..
    remove_packager xivo
    echo " "
}

main "$@"
