#!/bin/bash
# -*- coding: utf-8 mode: sh -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8
source "$(dirname -- "$0")/../load.sh" || exit 1
require: git pman pman.conf

################################################################################
# Informations
################################################################################

SHOW_VARS=(
    --Configuration
    "${CONFIG_VARS[@]}"
    --Paramètres
    CurrentBranch
    CurrentType=SrcType
)

function show_action() {
    local var src
    echo_setv ConfigBranch="$ConfigBranch"
    echo_setv ConfigFile="$(ppath "$ConfigFile")"
    for var in "${SHOW_VARS[@]}"; do
        if [ "${var#--}" != "$var" ]; then
            estep "${var#--}"
        else
            splitfsep "$var" = var src
            [ -n "$src" ] || src="$var"
            echo_setv "$var=${!src}"
        fi
    done
}

################################################################################
# Initialisation
################################################################################

function _init_config() {
    if [ ! -f .pman.conf -o -n "$ForceCreate" ]; then
        ac_set_tmpfile config
        cp "$ConfigFile" "$config"
        "${EDITOR:-nano}" "$config"
        [ -s "$config" ] || return 1

        cp "$config" .pman.conf
        if testdiff .pman.conf "$ConfigFile"; then
            ConfigFile="$(pwd)/.pman.conf"
            load_config
            load_branches current "$SrcBranch"
        fi
        git add .pman.conf
    fi
    if [ ! -f ".gitignore" ]; then
        echo >.gitignore "\
.~lock*#
.*.swp"
        git add .gitignore
    fi
    return 0
}

function init_repo_action() {
    local -a push_branches; local config

    [ ${#LocalBranches[*]} -eq 0 ] || die "Ce dépôt a déjà été initialisé"

    _init_config || exit_with ewarn "Initialisation du dépôt annulée"

    einfo "Création de la branche $MAIN"
    git symbolic-ref HEAD "refs/heads/$MAIN"
    git commit -m "commit initial"
    push_branches+=("$MAIN")

    einfo "Création de la branche $DEVELOP"
    git checkout -b "$DEVELOP"
    push_branches+=("$DEVELOP")

    _push_branches
}

function init_config_action() {
    local -a push_branches; config

    [ -f .pman.conf -a -z "$ForceCreate" ] && die "La configuration pman a déjà été initialisée"

    resolve_should_push

    _init_config || exit_with ewarn "Initialisation de la configuration annulée"
    git commit -m "configuration pman"
    push_branches+=("$CurrentBranch")

    _push_branches
}

function _ensure_main_branch() {
    [ -n "$MAIN" ] || die "La branche MAIN n'a pas été définie"
    [ -n "$MainBranch" ] || die "$MAIN: cette branche n'existe pas (le dépôt a-t-il été initialisé?)"
}

function checkout_main_action() {
    if [ -z "$MainBranch" ]; then
        array_contains AllBranches "$MAIN" && exit_with enote "\
$MAIN: une branche du même nom existe dans l'origine
    git checkout $MAIN"
        _ensure_main_branch
    fi
    git checkout -q "$MAIN"
}

function _ensure_develop_branch() {
    [ -n "$DEVELOP" ] || die "La branche DEVELOP n'a pas été définie"
    [ -n "$DevelopBranch" ] || die "$DEVELOP: cette branche n'existe pas (le dépôt a-t-il été initialisé?)"
}

function init_develop_action() {
    local -a push_branches

    if [ -z "$DevelopBranch" ]; then
        array_contains AllBranches "$DEVELOP" && exit_with enote "\
$DEVELOP: une branche du même nom existe dans l'origine
    git checkout $DEVELOP"
        _ensure_main_branch
        _ensure_develop_branch

        resolve_should_push

        enote "Vous allez créer la branche ${COULEUR_VERTE}$DEVELOP${COULEUR_NORMALE} <-- ${COULEUR_BLEUE}$MAIN${COULEUR_NORMALE}"
        ask_yesno "Voulez-vous continuer?" O || die

        einfo "Création de la branche $DEVELOP"
        git checkout -b "$DEVELOP" "$MAIN" || die
        push_branches+=("$DEVELOP")

        _push_branches
    fi
    git checkout -q "$DEVELOP"
}

function _ensure_upstream_branch() {
    [ -n "$UPSTREAM" ] || die "La branche UPSTREAM n'a pas été définie"
    [ -n "$UpstreamBranch" ] || die "$UPSTREAM: cette branche n'existe pas (le dépôt a-t-il été initialisé?)"
}

function init_upstream_action() {
    local -a push_branches; local config

    if [ -z "$UpstreamBranch" ]; then
        array_contains AllBranches "$UPSTREAM" && exit_with enote "\
$UPSTREAM: une branche du même nom existe dans l'origine
    git checkout $UPSTREAM"
        _ensure_develop_branch
        _ensure_upstream_branch

        resolve_should_push

        enote "Vous allez créer la branche ${COULEUR_VERTE}$UPSTREAM${COULEUR_NORMALE}"
        ask_yesno "Voulez-vous continuer?" O || die

        # faire une copie de la configuration actuelle
        ac_set_tmpfile config
        cp "$ConfigFile" "$config"

        einfo "Création de la branche $UPSTREAM"
        git checkout --orphan "$UPSTREAM" || die
        git rm -rf .
        cp "$config" .pman.conf
        git add .pman.conf
        git commit -m "commit initial"
        push_branches+=("$UPSTREAM")

        einfo "Fusion dans $DEVELOP"
        git checkout "$DEVELOP"
        git merge \
            --no-ff -m "<pman>Intégration initiale de la branche $UPSTREAM" \
            -srecursive -Xours --allow-unrelated-histories \
            "$UPSTREAM"
        push_branches+=("$DEVELOP")

        _push_branches
    fi
    git checkout -q "$UPSTREAM"
}

function _ensure_dist_branch() {
    [ -n "$DIST" ] || die "La branche DIST n'a pas été définie"
    [ -n "$DistBranch" ] || die "$DIST: cette branche n'existe pas (le dépôt a-t-il été initialisé?)"
}

function init_dist_action() {
    local -a push_branches

    if [ -z "$DistBranch" ]; then
        array_contains AllBranches "$DIST" && exit_with enote "\
$DIST: une branche du même nom existe dans l'origine
    git checkout $DIST"
        _ensure_main_branch
        _ensure_dist_branch

        resolve_should_push

        enote "Vous allez créer la branche ${COULEUR_VERTE}$DIST${COULEUR_NORMALE} <-- ${COULEUR_BLEUE}$MAIN${COULEUR_NORMALE}"
        ask_yesno "Voulez-vous continuer?" O || die

        einfo "Création de la branche $DIST"
        git checkout -b "$DIST" "$MAIN" || die
        push_branches+=("$DIST")

        _push_branches
    fi
    git checkout -q "$DIST"
}

function init_feature_action() {
    local -a push_branches; local branch

    [ -n "$FEATURE" ] || die "La branche FEATURE n'a pas été définie"
    branch="${1#$FEATURE}"
    [ -n "$branch" ] || die "Vous devez spécifier le nom de la branche"
    branch="$FEATURE$branch"

    if ! array_contains LocalBranches "$branch"; then
        array_contains AllBranches "$branch" && exit_with enote "\
$branch: une branche du même nom existe dans l'origine
    git checkout $branch"
        _ensure_develop_branch

        resolve_should_push

        enote "Vous allez créer la branche ${COULEUR_VERTE}$branch${COULEUR_NORMALE} <-- ${COULEUR_BLEUE}$DEVELOP${COULEUR_NORMALE}"
        ask_yesno "Voulez-vous continuer?" O || die

        einfo "Création de la branche $branch"
        git checkout -b "$branch" "$DEVELOP" || die
        push_branches+=("$branch")

        _push_branches
    fi
    git checkout -q "$branch"
}

function init_action() {
    local what="${1:-develop}"; shift
    case "$what" in
    init|repo|r) init_repo_action "$@";;
    config) init_config_action "$@";;
    main|m) checkout_main_action;;
    develop|dev|d) init_develop_action "$@";;
    upstream|up|u) init_upstream_action "$@";;
    dist|x) init_dist_action "$@";;
    *) init_feature_action "$what" "$@";;
    esac
}

################################################################################
# Programme principal
################################################################################

chdir=
ConfigBranch=
ConfigFile=
action=init
Origin=
[ -z "$PMAN_NO_PUSH" ] && Push=1 || Push=
ForceCreate=
args=(
    "gérer un projet git"
    "repo|config|develop|upstream|dist

INITIALISATION

Par défaut, le script agit en mode initialisation qui permet de créer et/ou
configurer certaines branches du dépôt si elles n'existent pas déjà

    repo
        initialiser un dépôt vide et créer les branches $MAIN et $DEVELOP
    develop
        créer la branche $DEVELOP
    upstream
        créer la branche ${UPSTREAM:-UPSTREAM} en tant que source de la branche $DEVELOP
    dist
        créer la branche ${DIST:-DIST} en tant que destination de la branche $MAIN
    anything
        créer la branche ${FEATURE}anything à partir de la branche $DEVELOP"
    -d:,--chdir:BASEDIR chdir= "répertoire dans lequel se placer avant de lancer les opérations"
    -B:,--config-branch ConfigBranch= "++\
branche à partir de laquelle charger la configuration"
    -c:,--config-file:CONFIG ConfigFile= "++\
fichier de configuration des branches. cette option est prioritaire sur --config-branch
par défaut, utiliser le fichier .pman.conf dans le répertoire du dépôt s'il existe"
    -w,--show-config action=show "++\
afficher la configuration chargée"
    --composer-select-profile action=composer_select_profile "\
sélectionner le profil composer spécifié en argument"
    -O:,--origin Origin= "++\
origine vers laquelle pousser les branches"
    -n,--no-push Push= "\
ne pas pousser les branches vers leur origine après leur création"
    --push Push=1 "++\
pousser les branches vers leur origine après leur création.
c'est l'option par défaut"
    -f,--force-create ForceCreate=1 "\
Avec config, forcer la (re)création du fichier .pman.conf"
)
parse_args "$@"; set -- "${args[@]}"

# charger la configuration
ensure_gitdir "$chdir"
load_branches all
load_config "$MYNAME"
load_branches current

# puis faire l'action que l'on nous demande
case "$action" in
show)
    show_action "$@"
    ;;
init)
    git_ensure_cleancheckout
    init_action "$@"
    ;;
composer_select_profile)
    exec "$MYDIR/_pman-$action.php" "$@"
    ;;
*)
    die "$action: action non implémentée"
    ;;
esac