#!/bin/bash

print_datetime() {
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] $1"
}

cd  ~/Desktop/Work4all-system/

echo "--------------------------------------------------------------------------------"
echo "--------------------------------------------------------------------------------" >> logs.txt

print_datetime "[From bash script] Starting infrastructure update checking process" 
print_datetime "[From bash script] Starting infrastructure update checking process" >> logs.txt

print_datetime "[From bash script] Retrieving update URL" >> logs.txt

filename="custom_config.txt"

while IFS= read -r line; do
    if [[ $line == "UPDATE_URL="* ]]; then
        url="${line#*=}"
        url="${url//[$'\n\r\t ']}"
        print_datetime "[From bash script] UPDATE_URL value in custom_config.txt: [$url]" >> logs.txt
    fi
    if [[ $line == "CUSTOMER_NUMBER="* ]]; then
        customer_number="${line#*=}"
        customer_number="${customer_number//[$'\n\r\t ']}"
        print_datetime "[From bash script] CUSTOMER_NUMBER value in custom_config.txt: [$customer_number]" >> logs.txt
    fi
    if [[ $line == "DB_HOST="* ]]; then
        db_host="${line#*=}"
        db_host="${db_host//[$'\n\r\t ']}"
        print_datetime "[From bash script] DB_HOST value in custom_config.txt: [$db_host]" >> logs.txt
    fi
    if [[ $line == "DB_PORT="* ]]; then
        db_port="${line#*=}"
        db_port="${db_port//[$'\n\r\t ']}"
        print_datetime "[From bash script] DB_PORT value in custom_config.txt: [$db_port]" >> logs.txt
    fi
    if [[ $line == "DB_USER="* ]]; then
        db_user="${line#*=}"
        db_user="${db_user//[$'\n\r\t ']}"
        print_datetime "[From bash script] DB_USER value in custom_config.txt: [$db_user]" >> logs.txt
    fi
    if [[ $line == "ROOT_PASSWORD="* ]]; then
        root_password="${line#*=}"
        root_password="${root_password//[$'\n\r\t ']}"
        print_datetime "[From bash script] ROOT_PASSWORD value in custom_config.txt: [$root_password]" >> logs.txt
    fi
    if [[ $line == "PASSWORD="* ]]; then
        db_password="${line#*=}"
        db_password="${db_password//[$'\n\r\t ']}"
        print_datetime "[From bash script] PASSWORD value in custom_config.txt: [$db_password]" >> logs.txt
    fi
    if [[ $line == "API_KEY="* ]]; then
        api_key="${line#*=}"
        api_key="${api_key//[$'\n\r\t ']}"
        print_datetime "[From bash script] API_KEY value in custom_config.txt: [$api_key]" >> logs.txt
    fi
done < "$filename"

cd linux_updates

rm perform_installation

curl "https://api.${url}/update_system?number=${customer_number}&apikey=${api_key}&os=u22" -k -o perform_installation &&

cd .. &&

chmod +x linux_updates/perform_installation &&
linux_updates/perform_installation "unconditional"