#!/bin/bash
# Copyright 2010-2014 Chad Lemmen http://www.lemmen.com

file=$1
host=$2

if [ $# != 2 ]; then
    echo "Usage: $0 [filename] [remote_host]"
    exit 3
fi

# Function to check if a vpn interface is up.
vpn_up() {
  netstat -r | grep -q tun0
  if [ $? -eq 0 ]; then
    # VPN is up
    return 0 
  fi

  return 1
}

# Function to disconnect the vpn connection
discon_vpn() {
  if [ "$vpn" = "Y" ]; then
    # Bring down the vpn connection
    sudo $vpncdisconnect
    # This was needed for the promo, since two files are sent for each store
    # and the 2nd sent beat the vpn interface going down, it takes a second
    # for it to go down after the disconnect is run.
    sleep 1
    vpn=""
  fi
}

# Cannot pipe to eval so instead put command into 
# an array and execute the entire array when called.
sshcmd=(ssh -oStrictHostKeyChecking=no)

# flag -t for timeout doesn't work defaults to a few min.    
putcmd="ncftpput -t10 -a -u GilbarcoFTP -p XMLUser4FTP 10.5.60.1"
getcmd="ncftpget -t10 -a -u GilbarcoFTP -p XMLUser4FTP 10.5.60.1"

# Determine if it's a vpn connection or ssh.  SSH uses the format user@hostname
echo "$host" | grep -q '@' 
if [ $? -ne 0 ] && [ "$host" != "localhost" ]; then # It must be a vpn
  # Set these to the path of your vpnc commands
  vpnc=/usr/local/sbin/vpnc
  vpncdisconnect=/usr/local/sbin/vpnc-disconnect

  # If a vpn connection is up it may be in use so exit
  if vpn_up; then
    exit 1
  fi

  # Bring up the vpn connection
  sudo $vpnc "$host" # This will read the /etc/vpnc/$host.conf config file

  # Make sure the vpn connection is up
  if ! vpn_up; then
    # Transfer failed
    exit 1
  fi

  # Now that the vpn connection is up treat it as a local connection
  host="localhost"
  vpn="Y"
fi 
  
if [ "$host" = "localhost" ]; then
  # If a vpn connection is up it may be in use so exit
  if vpn_up arg && [ "$vpn" != "Y" ]; then
    exit 1
  fi

  $putcmd boinbox "$file" > /dev/null 2>&1

  if [ $? -ne 0 ]; then
    # If the transfer command fails and it's a vpn, bring it down
    discon_vpn

    # Transfer failed
    exit 1
  fi

  # If the uploaded file format is bad a DEAD file will be created
  $getcmd /usr/tmp booutbox/DEAD* > /dev/null 2>&1 

  if [ $? -eq 0 ]; then
    # If the transfer command fails and it's a vpn, bring it down
    discon_vpn

    # DEAD file exists!
    exit 2
  fi

else

  gzip -c "$file" | "${sshcmd[@]}" $host "gunzip - | ncftpput -t 5 -a -u GilbarcoFTP -p XMLUser4FTP -c 10.5.60.1 boinbox/`basename $file`"

  # ssh returns the exit status of the remote command  
  if [ $? -ne 0 ]; then
    # Transfer failed
    exit 1
  fi

  # If the uploaded file format is bad a DEAD file will be created
  "${sshcmd[@]}" $host "$getcmd /usr/tmp booutbox/DEAD* > /dev/null 2>&1"

  # ssh returns the exit status of the remote command
  if [ $? -eq 0 ]; then
    # DEAD file exists!
    exit 2
  fi
fi

# Bring down the vpn connection
discon_vpn

