#!/bin/bash

exec 3>/tmp/build_error.log

function error {
    >&2 printf "\e[31mE\e[0m: %s\n" "$1"
}

function get_current_dir {
    # this function return the absolute path of the script
    
    local script_path
    script_path="$(dirname $0)"

    # If the path begin with /, this is an absolute part
    if [[ "$script_path" =~ ^/[[:graph:]]*$ ]]
    then
        printf "%s" "$script_path"
        return 
    fi

    local current_path
    current_path="$(pwd)"
    if [[ $script_path == "." ]]
    then
        script_path=""
    elif [[ $script_path =~ ^./[[:graph:]]*$ ]]
    then
        script_path=${script_path##./}
        echo " $current_path trad: $script_path"
    else
        while [[ $script_path =~ ^../[[:graph:]]*$ ]]
        do
            script_path="${script_path##../}"
            current_path="${current_path%/*}"
        done
    fi
    printf "%s/%s" "${current_path}" "${script_path}"

}

current_dir=$(get_current_dir)
scripts_dir="${current_dir}/scripts"

cd /tmp || { error "Can't go into /tmp"; exit 1; }
for script in ${scripts_dir}/*.sh
do
    source $script
    printf "\nBuilding %s\n" "$name"
    printf "  >> cloning repository\n"
    $clone_command 2>&3 || {
        error "Error when cloning $name"
        exit 1
    }
    post_clone_hook

    cd $clone_directory   
    if [[ ! $patches_dir == 0 ]]
    then
        printf "  >> patching\n"
        for patch in ${current_dir}/${patches_dir}/*
        do
            printf "   >  patchfile: %s" "$patch"
            patch -p1 < "$patch" || {
                error "Error whan applying patch, check log\n"; 
                exit 1; 
            }
        done
    fi

    printf "  >> configure\n"
    $configure_command 2>&3 1>/dev/null|| {
        error "Error when configuring $name, command: $configure_command"
        exit 1
    }
    post_configure_hook
    
    printf "  >> Build and install\n"
    $build_command 2>&3 || {
        error "Error when buildind and installing $name, command: $build_command"
        exit 1
    }
    cd ..
    post_install_hook
done
exit 0
