#!/bin/bash

# MARK: Prepare variable for auto fill contents
TS_START=$(date +20%y%m%d-%H%M%S:%Z)

# MARK: Base tmp dir
T_NAME='apt_dnf_auto.bashrc'
TMP_DIR=$(mktemp -d -t ci-$(date +%Y-%m-%d-%H-%M-%S)-XXXXXXXXXX)
T_TMP_PATH="${TMP_DIR}/${T_NAME}"


T_BASHRC_NAME="${T_NAME}"
T_MIRROR_HOST='kr.mirrors.naho.moe'
T_PROTO_SCHEME='https'
T_BASE_PATH='/naho/tools'

T_URI="${T_PROTO_SCHEME}://${T_MIRROR_HOST}${T_BASE_PATH}/${T_BASHRC_NAME}"

# MARK: Download working files on tmp directory just made
echo 'Downloading the latest bashrc file...'
echo " → URI: ${T_URI} ..."
echo ''
curl "${T_URI}" --output "${T_TMP_PATH}"

# MARK: Replace CONSTANTS
echo "Replacing CONSTANTS to variable with current executed environments ..."
echo " → REPLACE_DL_FROM: ${T_URI}"
echo " → APPENDED_AT: ${TS_START}"
echo ''
sed -i "s|REPLACE_DL_FROM|${T_URI}|g" "${T_TMP_PATH}"
sed -i "s|APPENDED_AT|${TS_START}|g" "${T_TMP_PATH}"
echo '' && \
echo '' && \


# MARK: Reflecting the final changes on the /etc/profile file ...
echo 'Reflecting the final changes on the /etc/profile file...' && \
if [[ ! -f '/etc/apt_dnf_auto.bashrc' ]]; then
	echo '' >> /etc/profile && \
	echo '' >> /etc/profile && \
	echo '### MARK: apt_dnf_auto alias tools from mirrors.naho.moe' >> /etc/profile && \
	echo 'source /etc/apt_dnf_auto.bashrc' >> /etc/profile && \
	echo '' >> /etc/profile && \
	echo '' >> /etc/profile
fi
cp -pf ${T_TMP_PATH} '/etc/apt_dnf_auto.bashrc' && \
echo '' && \
echo 'Finished to install apt & dnf util successfully!' && \
echo '' && \
echo 'You can use it for `apt_init` or `dnf_init` fot install utilities,' && \
echo ' use `apt_auto` or `dnf_auto` for update repo cache, update all packes and clean all caches' && \
echo ''
echo " Ah, please don't forget to re-open your console!"
echo ''
