#!/bin/bash

. /usr/lib/network/network

NETCFG_VER=3.0

version()
{
    echo "netcfg v$NETCFG_VER"
}

usage()
{
    version
    cat << END
Usage:
      Start specified profile:    netcfg profile
      Other functions:            netcfg argument profile
Arguments:
    current        Report currently running profiles
-a, all-down       Take all active profiles down
-c, check-iface    Do not start profile if interface is already up
-d, down           Take specified profile down
-D, iface-down     Take down profile active on specified interface
-h, help           This help message
-l, list           List all available profiles
-r, reconnect      Disconnect and reconnect specified profile
-R, iface-recon    Reconnect profile active on specified interface
-u, up             Start specified profile
-v, version        Output version information and exit
    all-resume     Resume previously suspended profiles and reconnect them
    all-suspend    Store a list of current running profiles and suspend them
END
}

# TODO: Re-add ROOT check and rewrite with getopts from BashFAQ

case "$1" in
    --version|-v|version)
        version
        exit 0;;
    --help|-h|help)
        usage
        exit 0;;
    list|-l)
        list_profiles
        exit 0;;
    current|-s|status)
        if [[ -d "$STATE_DIR/profiles/" ]]; then
            ls "$STATE_DIR/profiles/"
            exit 0
        else
            exit_stderr "No active profiles."
        fi;;
esac

if [[ $(id -u) -gt 0 ]]; then
    exit_stderr "This script should be run as root."
fi

# Ensure cwd is not in a transient directory, which may prevent unmounting due to netcfg children
cd /

case "$1" in
    -c|check-iface|-u|up)
        CHECK="YES"
        profile_up "$2";;
    -d|down)
        profile_down "$2";;
    -D|iface-down)
        interface_down "$2";;
    -a|all-down)
        all_down;;
    -r|reconnect)
        profile_down "$2"
        profile_up "$2";;
    -R|iface-recon)
        interface_reconnect "$2";;
    all-resume)
        all_resume;;
    all-suspend)
        all_suspend;;
    clean)
        rm "$STATE_DIR/interfaces"/* 2> /dev/null
        rm "$STATE_DIR/profiles"/* 2> /dev/null
        rm "$STATE_DIR/suspend"/* 2> /dev/null
        rm "$STATE_DIR/netcfg-daemon" 2> /dev/null
        killall wpa_supplicant 2> /dev/null
        killall dhcpcd 2> /dev/null
        killall dhclient 2> /dev/null
        ;;
    -*|--*)
        usage
        exit 1;;
    *)
        if [[ -n "$1" ]]; then
            profile_up "$1"
        else
            usage
            exit 1
        fi
        ;;
esac
exit $?

# vim: ft=sh ts=4 et sw=4:
