#!/usr/bin/env bash

set -e

ok() {
    message=$1
    printf "\033[1;37m${message}\033[0m\n"
}

replaceLine() {
    local search
    local replacement
    local file
    search=$1
    replacement=$2
    replacementRaw=${replacement}
    file=$3

    echo " - ${file} - \"${search}\" -> \"${replacement}\"";

    #escape
    search=$(echo "${search}" | sed -e 's/[\/&]/\\&/g')
    replacement=$(echo "${replacement}" | sed -e 's/[\/&]/\\&/g')

    sed -i "/${search}/ c\\${replacement}" "${file}"

    if [[ -z $(cat "${file}" | grep -F "${replacementRaw}") ]]
    then
        echo "${file} not changed (search: \"${search}\", replacement: \"${replacement}\")"
        echo "File content:"
        cat "${file}"
        die "Exiting due errors"
    fi
}

replaceLineStarting() {
    local search
    local replacement
    local file
    search=$1
    replacement=$2
    replacementRaw=${replacement}
    file=$3

    echo " - ${file} - \"${search}\" -> \"${replacement}\"";

    #escape
    search=$(echo "${search}" | sed -e 's/[\/&]/\\&/g')
    replacement=$(echo "${replacement}" | sed -e 's/[\/&]/\\&/g')

    sed -i "/^${search}/ c\\${replacement}" "${file}"

    if [[ -z $(cat "${file}" | grep -F "${replacementRaw}") ]]
    then
        echo "${file} not changed (search: \"${search}\", replacement: \"${replacement}\")"
        echo "File content:"
        cat "${file}"
        die "Exiting due errors"
    fi
}

change() {
    local how
    local file
    how=$1
    file=$2

    echo " - ${file} - \"${how}\"";
    sed -i "${how}" "${file}"
}

append() {
    local what
    local file
    what=$1
    file=$2

    echo -e "${what}" >> "${file}"
}

create() {
    local what
    local file
    what=$1
    file=$2

    echo -e "${what}" > "${file}"
}

die() {
    echo "$@" 1>&2
    exit 1
}