#!/bin/sh

localEcho=0
if [ "$1" = "echo" ]; then
  localEcho=1;
  cmp=$2
  usr=$3
  pass=$4
else
  cmp=$1
  usr=$2
  pass=$3
fi

if [ "$cmp" = "" ] || ([ "$usr" != "" ] && [ "$pass" = "" ]); then
  script=`basename $0`
  echo
  echo "Usage: $script [echo] campaignId [user] [token]";
  echo
  echo "[echo] is optional. If included, anything sent to the pipe will be echoed locally on stderr"
  echo "If you are not using an account, you must get the campaignId from https://pipe2.net"
  echo "If you have an account, you must enter your username and token as the second and third arguments. If the specified campaignId doesn't exist, it will be automatically created."
  echo
  exit 1;
fi

# Use the publicly distributed private key to access the server.

# 1. Put it in a file
cat > /tmp/p2w_pk<< EOF
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACCGJKOQMJEENa3XoFT+GRLvG33mFkxYedtzDfjG2NR81wAAAJDN4Qi+zeEI
vgAAAAtzc2gtZWQyNTUxOQAAACCGJKOQMJEENa3XoFT+GRLvG33mFkxYedtzDfjG2NR81w
AAAECzNUyPlqzVNMYqzkA/Z5kxGexYKdoQGUIytRzh+8nYdYYko5AwkQQ1rdegVP4ZEu8b
feYWTFh523MN+MbY1HzXAAAADXJvb3RAdWJ1bnR1MjI=
-----END OPENSSH PRIVATE KEY-----
EOF

# 2. Change the permissions so ssh accepts it
chmod go-rwx /tmp/p2w_pk

# 3. Pipe the output to ssh using the tmp file
if [ "$localEcho" = "1" ]; then
  (echo "$cmp/$usr/$pass" && tee /dev/stderr) | ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -T -i /tmp/p2w_pk pipe@pipe2.net
else
  (echo "$cmp/$usr/$pass" && cat) | ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -T -i /tmp/p2w_pk pipe@pipe2.net
fi
# 4. Remove the tmp file
rm /tmp/p2w_pk
