#!/bin/bash

. /usr/lib/eole/ihm.sh

export LVM_SUPPRESS_FD_WARNINGS=1

function percentage_to_pe()
{
    echo `expr $FREE_PE \* $1 / 100`
}

function extend_lv()
{
    local size=$2
    if [[ "${size}" = "0" ]]
    then
        echo "Nothing to do for ${1}"
        return 0
    elif [[ "${size}" = "" ]]
    then
        size="100%FREE"
    fi
    echo "Extending ${1} with $size"
    lvextend -l +$size ${LV_ROOT_PATH}/${1} -r > /dev/null 2>&1
    wait ${!}
    return 0
}

function create_lvs()
{
    local lv_name=${LV_ROOT_PATH}/$1
    local lv_size=`percentage_to_pe $2`
    local lv_format=$3
    echo "Creating LV $lv_name of $lv_size PE"
    lvcreate -n $lv_name -l $lv_size > /dev/null 2>&1
    wait ${!}
    if [[ "${lv_format}" != "None" ]]
    then
        echo "Creating fs $lv_format"
        /sbin/mkfs.$lv_format $lv_name > /dev/null 2>&1
        wait ${!}
    fi
    return 0
}

function get_index() {
    my_array=( "${@:2}" )
    for i in "${!my_array[@]}"; do
        if [[ "${my_array[$i]}" = "$1" ]]; then
            echo "${i}";
        fi
    done
}

function order_mount_points() {
    elements=( "$@" )
    local processed=''
    IFS=$'\n' sorted=( $(sort <<<"${elements[*]}") )
    unset IFS
    for element in "${sorted[@]}"; do
        indexes="$(get_index $element "${elements[@]}")"
	# ${indexes} can have multiple entries for None
	for index in ${indexes};
	do
	    if [[ "${processed}" =~ ";${index};" ]]
	    then
		# Do not store 2 times the same entry
		continue
	    else
		processed="${processed};${index};"
		echo ${index}
	    fi
	done
    done
}

function create_fstab_entry() {
    local lv_path=${LV_ROOT_PATH}/$1
    local lv_uuid=$(blkid -s UUID ${LV_ROOT_PATH}/$1 | cut -d ' ' -f 2)
    local lv_mount_point=$2
    local lv_format=$3
    local lv_mount_options=$4
    if [[ "${lv_mount_point}" != "None" ]] && [[ "${lv_uuid}" != "" ]] && [[ ! "$lv_mount_point" =~ [[:space:]]+${lv_mount_point}[[:space:]]+ ]]
    then
        echo "Creating fstab entry for $lv_path on $lv_mount_point"
        echo "${lv_uuid//\"/} $lv_mount_point $lv_format ${lv_mount_options/None/rw} 0 2" >> /etc/fstab
        if [[ -d "$lv_mount_point" ]]
        then
            EchoOrange "Transfert des données"
            for process in `lsof | awk -v mount_point="${lv_mount_point//\//\\\/}" '$0 ~ mount_point {print $2}' | uniq`
            do
                if [[ ! "$PIDS" =~ "(${process})" ]]
                then
                    kill "${process}"
                fi
            done
            temp_mount_point=$(mktemp -d)
            mount $lv_path $temp_mount_point
            cp -a $lv_mount_point/* $temp_mount_point
            wait ${!}
            rm -rf $lv_mount_point/*
            umount $temp_mount_point
        else
            mkdir -p $lv_mount_point
        fi
        mount -a
        if [[ "${lv_mount_options}" =~ quota ]]
        then
            if [ ! -e /sbin/quotacheck ]
            then
                EchoOrange "Installer le paquet quota et lancer la commande quotacheck -cgum ${lv_mount_point} pour finaliser l’activation des quotas."
            else
                quotacheck_options="-cm"
                quotaon_options="-"
                if [[ "${lv_mount_options}" =~ usrquota ]]
                then
                    quotacheck_options="${quotacheck_options}u"
                    quotaon_options="${quotaon_options}u"
                fi
                if [[ "${lv_mount_options}" =~ grpquota ]]
                then
                    quotacheck_options="${quotacheck_options}g"
                    quotaon_options="${quotaon_options}g"
                fi
                quotacheck "${quotacheck_options}" "${lv_mount_point}"
                quotaon ${quotaon_options} ${lv_mount_point}
                quotaon -p ${lv_mount_point}
            fi
        fi
    else
        echo "No fstab entry created for $lv_path"
    fi
    return 0
}

if [[ $(CreoleGet allow_manual_partitioning non) = 'oui' ]] && [[ "$1" = "instance" ]]
then
    LV_ROOT_PATH=`dirname $(vgs -o lv_path --noheadings | head -n1)`
    FREE_PE=`vgs -o vg_free_count --noheadings`
    LV_NAMES=`lvs -o lv_name --noheadings`
    MOUNT_POINTS="`awk '/^[^#]+$/ {print $2}' /etc/fstab`"
    PIDS=`pstree -ps $$`

    # Use EOLE standard extension or personalisez one
    if [[ $(CreoleGet use_eole_standard_volume_extension non) = 'oui' ]]
    then
        partitioning_lv_name=( $(CreoleGet eole_lv_names) )
        partitioning_lv_size=( $(CreoleGet eole_lv_standard_extends) )
        # Just count elements
        indices=$(seq 0 $(( ${#partitioning_lv_name[@]} - 1 )) )
    elif [[ $(CreoleGet partitioning_create_lv non) = 'oui' ]]
    then
        partitioning_lv_name=( `CreoleGet partitioning_lv_name` )
        partitioning_lv_size=( $(CreoleGet partitioning_lv_size) )
        partitioning_lv_format=( `CreoleGet partitioning_lv_format` )
        partitioning_lv_mount_point=( `CreoleGet partitioning_lv_mount_point` )
        partitioning_lv_mount_options=( `CreoleGet partitioning_lv_mount_options` )
        indices="$(order_mount_points ${partitioning_lv_mount_point[@]})"
    fi

    for index in $indices
    do
        EchoGras "Traitement du volume logique ${partitioning_lv_name[$index]}"
        if [[ "${LV_NAMES}" =~ [[:space:]]+"${partitioning_lv_name[$index]}"([[:space:]]+|$) ]]
        then
            extend_lv "${partitioning_lv_name[$index]}" `percentage_to_pe ${partitioning_lv_size[$index]}`
        else
            create_lvs ${partitioning_lv_name[$index]} \
                       ${partitioning_lv_size[$index]} \
                       ${partitioning_lv_format[$index]}

            create_fstab_entry ${partitioning_lv_name[$index]} \
                               ${partitioning_lv_mount_point[$index]} \
                               ${partitioning_lv_format[$index]} \
                               ${partitioning_lv_mount_options[$index]}
        fi
    done

    if [[ "`CreoleGet partitioning_lv_extend non`" = "oui" ]]
    then
        extend_lv "`CreoleGet partitioning_lv_to_extend`"
    fi
fi
exit 0
