#!/bin/bash

MYSELF=$( basename $0 )

script_help() {
    cat <<EOF
${MYSELF} help:

Restart a network device

Usage: ${MYSELF} -d <DEVICE>

where:
    DEVICE ... eth0|eth1|tun0

EOF
}

if [[ $# -lt 2 ]]
then
    script_help
    exit 1
fi

while getopts "d:" option
do
    case ${option} in
    d)  DEVICE=$OPTARG
        ;;
    *)  script_help
        exit 2
        ;;
    esac
done

if [[ $UID -gt 0 ]]
then
    echo "$MYSELF needs to be run as superuser. You are $USER."
    exit 3
fi

NOHUP="/usr/bin/nohup"
SH="/bin/sh"
DOWN="/sbin/ifdown"
UP="/sbin/ifup"

# re-init a network device by taking it down and up; usage of nohup should help to avoid lost ssh connections
if [[ -n "$DEVICE" ]]
then
    ${NOHUP} ${SH} -c "${DOWN} ${DEVICE}; sleep 2; ${UP} ${DEVICE}" >/dev/null 2>&1 &
fi

exit 0
