#!/bin/bash

ACTION=$1

if [ -z $ACTION ]; then
    echo "Usage: $0 <start|stop>"
    exit 0
fi

CONFIG='/etc/bonding/troubleshooting-address.conf'

if [ ! -f "$CONFIG" ]; then
    echo "Error: File '$CONFIG' not found." >&2
    exit 1
fi

IS_ENABLE=$(grep '^enable *=' $CONFIG | cut -d '=' -f2 | xargs)
if [ "$IS_ENABLE" == "false" ]; then
    echo "Troubleshooting IP is disabled"
    exit 0
fi

INTERFACE=$(grep '^interface *=' $CONFIG | cut -d '=' -f2 | xargs)
ADDRESS=$(grep '^ip_address *=' $CONFIG | cut -d '=' -f2 | xargs)

case $ACTION in
start)
    if [ -z "$INTERFACE" ]; then
        echo "Error: No interface found in '$CONFIG'." >&2
        exit 1
    fi

    ip link set $INTERFACE up
    echo "Adding troubleshooting IP address $ADDRESS to $INTERFACE"
    ip address add $ADDRESS dev $INTERFACE || {
        echo "Error: Failed to assign IP address for interface '$INTERFACE'." >&2
        exit 1
    }
    ;;
stop)
    echo "Removing troubleshooting IP address $ADDRESS from $INTERFACE"
    ip address delete $ADDRESS dev $INTERFACE
    ;;
*)
    echo "Invalid action $ACTION"
    exit 1
    ;;
esac
