#!/usr/bin/env bash

scriptpath="`readlink -f \"$0\"`"
scriptbase="`dirname \"${scriptpath}\"`"

. "${scriptbase}/migrate-tools"

DEFAULT_PROXY_SERVER="dosis_user:WgPcGr98@3.21.95.229:3337"
PROXY_SERVER=${DEFAULT_PROXY_SERVER}
OS="`getos`"

function error() {
    echo -e "\033[031m$1\033[0m"
}

function repl() {
    line=$1
    repl=$2
    targ=$3

    mkdir -p `dirname $targ`
    (grep $line $targ && sed -i -re "s,$line.*,$repl,g" $targ) || (printf "\n$repl" >> $targ)
}

if [ ${UID} != 0 ]; then
    error "This script must be ran as root"
    exit 1
fi

if [ "${OS}" = "CentOS" ]; then
    echo "Detected ${OS}: Patching Repo Files"

    PATCH_FILES_CONFIG=(
        "base,updates,extras,centosplus,contrib:/etc/yum.repos.d/CentOS-Base.repo"
        "epel,epel-debuginfo,epel-source:/etc/yum.repos.d/epel.repo"
        "epel-testing,epel-testing-debuginfo,epel-testing-source:/etc/yum.repos.d/epel-testing.repo"
        "PUIAS_6_computational:/etc/yum.repos.d/puias-computational.repo"
        "rpmfusion-free-updates,rpmfusion-free-updates-debuginfo,rpmfusion-free-updates-source:/etc/yum.repos.d/rpmfusion-free-updates.repo"
        "rpmfusion-free-updates-testing,rpmfusion-free-updates-testing-debuginfo,rpmfusion-free-updates-testing-source:/etc/yum.repos.d/rpmfusion-free-updates-testing.repo"
    )

    for fc in ${PATCH_FILES_CONFIG[@]}; do
        file="`echo ${fc} | cut -d: -f2`"
        sections="`echo ${fc} | cut -d: -f1 | sed 's/,/ /g'`"

        for s in ${sections}; do
            echo "Patching [${s}] ${file}"
            sed -i -re "/\[${s}\]/,/\[/s/#*baseurl=/#baseurl=/g" "${file}"
            sed -i -re "/\[${s}\]/,/\[/s/#+mirrorlist=/mirrorlist=/g" "${file}"
        done
    done

    sed -i '/proxy=_none_/d' "/etc/yum.repos.d/Dosis.repo" 

    /opt/dosis2/bin/conf-edit "/etc/yum.conf" --output "/etc/yum.conf" \
        --delete main.proxy

    repl "proxy=http://$PROXY_SERVER" "" "/etc/yum.conf"
elif [ "${OS}" = "Ubuntu" ]; then
    rm -f /etc/apt/apt.conf.d/97proxy
else
    error "Unknown OS: ${OS}"
    exit 1
fi

rm -f /opt/dosis2/etc/bashrc.d/97-proxy

. "${scriptbase}/unset-proxy-vars"
