#!/bin/bash
set -e

mkdir -p /var/lib/local-installer-agent
mkdir -p /var/log/local-installer-agent
mkdir -p /var/cache/local-installer-agent/packages
mkdir -p /etc/local-installer-agent

AGENT_ENV="/etc/local-installer-agent/agent.env"
touch "$AGENT_ENV"

set_agent_env() {
    KEY="$1"
    VALUE="$2"

    if grep -q "^$KEY=" "$AGENT_ENV"; then
        sed -i "s|^$KEY=.*|$KEY=$VALUE|" "$AGENT_ENV"
    else
        echo "$KEY=$VALUE" >> "$AGENT_ENV"
    fi
}

append_csv_env() {
    KEY="$1"
    VALUE="$2"

    CURRENT="$(grep "^$KEY=" "$AGENT_ENV" | tail -n 1 | cut -d= -f2- || true)"
    if [ -z "$CURRENT" ]; then
        set_agent_env "$KEY" "$VALUE"
        return
    fi

    case ",$CURRENT," in
        *",$VALUE,"*) ;;
        *) set_agent_env "$KEY" "$CURRENT,$VALUE" ;;
    esac
}

set_agent_env ALLOW_DOCKER true
set_agent_env AUTO_INSTALL_DOCKER true
append_csv_env ALLOWED_DOCKER_REGISTRIES docker.io

cd /opt/local-installer-agent

if [ ! -d "venv" ]; then
    python3 -m venv venv
fi

./venv/bin/pip install --upgrade pip
./venv/bin/pip install -r requirements.txt

systemctl daemon-reload
systemctl enable local-installer-agent
systemctl restart local-installer-agent

exit 0
