#!/bin/sh

TMPDIR=~iworx/tmp/support
IW_SUPPORT=iworx_support_user
IW_UID=62221
SSH_CONFIG=/etc/ssh/sshd_config
SUDOERS=/etc/sudoers
HOSTS_ALLOW=/etc/hosts.allow

function prep {
    [ -e $TMPDIR ] && rm -rf $TMPDIR
    mkdir $TMPDIR
}

function kill_user {
    if [ "`logname 2>/dev/null`" != "$IW_SUPPORT" ]; then
        pids=`ps --no-headers -o pid -U $IW_UID -u $IW_UID 2> /dev/null`
        [ "$pids" != "" ] && kill -HUP $pids > /dev/null 2>&1
    fi
    /usr/sbin/userdel -r -f $IW_SUPPORT
    echo "User deleted: $IW_SUPPORT"
}

function clean_hosts {
    grep '^sshd: 208.69.120.3$' $HOSTS_ALLOW > /dev/null 2>&1
    if [ "$?" -eq "0" ]; then
        grep -v '^sshd: 208.69.120.3$' $HOSTS_ALLOW | grep -v $IW_SUPPORT | cat -s - > $TMPDIR/hosts.allow
        /bin/cp $TMPDIR/hosts.allow $HOSTS_ALLOW
        echo "Removed iworx support server from $HOSTS_ALLOW"
    fi
}

function clean_ssh {
    grep "^AllowGroups $IW_SUPPORT" $SSH_CONFIG > /dev/null 2>&1
    groups=$?
    grep "^AllowUsers $IW_SUPPORT" $SSH_CONFIG > /dev/null 2>&1
    users=$?

    if [[ $users -eq 0 || $groups -eq 0 ]]; then
        grep -v $IW_SUPPORT $SSH_CONFIG | cat -s - > $TMPDIR/sshd_config
        /bin/cp $TMPDIR/sshd_config $SSH_CONFIG
        echo "Removed $IW_SUPPORT from $SSH_CONFIG"
    fi
}

function clean_sudo {
    grep "$IW_SUPPORT" $SUDOERS > /dev/null 2>&1
    if [ "$?" -eq "0" ]; then
        grep -v $IW_SUPPORT $SUDOERS | cat -s - > $TMPDIR/sudoers
        /bin/cp $TMPDIR/sudoers $SUDOERS
        echo "Removed $IW_SUPPORT from $SUDOERS"
    fi
}

function clean_firewall {
    fwlines=`/sbin/iptables --list -n | wc -l`
    if [ $fwlines -gt 8 ]; then
        /usr/local/sbin/apf -u 208.69.120.3 > /dev/null 2>&1
        echo "Removed login.interworx.com firewall config"
    fi
}

function finish {
    echo "Done! SSH for $IW_SUPPORT now disabled"
    rm -rf $TMPDIR
    rm ~iworx/tmp/.ssh-support-enabled > /dev/null 2>&1
    if [ "`logname 2>/dev/null`" == "$IW_SUPPORT" ]; then
        echo "PLEASE LOGOUT NOW"
    fi
}

prep
kill_user
clean_hosts
clean_ssh
clean_sudo
clean_firewall
finish

