#!/bin/sh
set -e

if [ "$1" = "1" ] || [ "$1" = "2" ]; then
    DATA_DIR="/var/lib/vyoma"
    BIN_DIR="${DATA_DIR}/bin"

    # Ensure directories exist and have proper permissions
    mkdir -p "${BIN_DIR}"
    chown -R vyoma:vyoma "${DATA_DIR}"
    chmod 755 "${DATA_DIR}"
    chmod 755 "${BIN_DIR}"
    
    if [ -f "${BIN_DIR}/cloud-hypervisor" ]; then
        chmod +x "${BIN_DIR}/cloud-hypervisor"
    fi
    
    if [ -f "${BIN_DIR}/vyoma-agent-vm" ]; then
        chmod +x "${BIN_DIR}/vyoma-agent-vm"
    fi

    # Create vyoma0 bridge if it doesn't exist
    if ! ip link show vyoma0 > /dev/null 2>&1; then
        ip link add name vyoma0 type bridge
        ip addr add 172.16.0.1/24 dev vyoma0 || true
        ip link set dev vyoma0 up
    fi

    # Reload systemd and enable/start the service
    systemctl daemon-reload || true
    systemctl enable vyomad.service || true
    systemctl restart vyomad.service || true
fi
exit 0
