#!/bin/bash

HELP="
 This is a simple script for manipulating files in
 the Extremely Corporate vault. Usage is as follows:

   1) Uploading a file:
       vault.sh path/in/vault path/to/file

   2) Removing a file:
       vault.sh rm path/in/vault

   3) Moving a file:
       vault.sh mv path/in/vault path/in/vault

   4) Downloading a file:
       vault.sh get path/in/vault

   5) List files:
       vault.sh ls path/in/vault

   6) Creating a directory:
       vault.sh mkdir path/in/vault

   7) Mounting the vault (requires sshfs)
       vault.sh mount path/in/vault path/to/local/mountpoint

   8) Update vault.sh
       vault.sh update

 **Note: Make sure you prefix your paths in the vault
           with the name of the vault you would like
           to access (e.g. 'videos', 'vault', etc.)

"

if [ -z $1 ]; then
    echo "$HELP"
    exit 1
fi

SERVER_ADDRESS='extremelycorporate.ca'
PORT='1222'
USER=vault
VAULT_PATH="/home/${USER}/vault"

case ${1} in
mv)
    # Move a file to another location in the vault
    file_to_move="${VAULT_PATH}/$2"
    destination="${VAULT_PATH}/$3"
    ssh -p $PORT ${USER}@${SERVER_ADDRESS} \
        "mv ${file_to_move@Q} ${destination@Q} && exit"
    ;;
mkdir)
   # Create a directory in the vault
   dir="${VAULT_PATH}/$2"
   ssh -p $PORT ${USER}@${SERVER_ADDRESS} \
      "mkdir ${dir@Q} && exit"
   ;;
rm)
    # Remove a file from the vault

    # This is a simple check to prevent accidents. Make sure the path does
    # not have depth 1, i.e. prevent deleting entire sections of the vault
    if [[ "$2" != *?/?* ]]; then
        echo "Be careful!"
        exit 1
    fi
    file_to_remove="${VAULT_PATH}/$2"
    ssh -p $PORT ${USER}@${SERVER_ADDRESS} \
        "rm -rf ${file_to_remove@Q} && exit"
    ;;
ls)
    dir_to_list="${VAULT_PATH}/$2"
    ssh -p $PORT ${USER}@${SERVER_ADDRESS} \
        "ls -l ${dir_to_list@Q} && exit"
    ;;
get)
    # Download a file from the vault
    file_to_get=${VAULT_PATH}/$2
    if [ -z $3 ]; then
        dest_path="."
    else
        dest_path=${3@Q}
    fi
    scp -r -P $PORT $USER@$SERVER_ADDRESS:${file_to_get@Q} $dest_path
    ;;
mount)
   sshfs -o follow_symlinks ${USER}@${SERVER_ADDRESS}:${VAULT_PATH}/${2} ${3}
   ;;
update)
    curl https://$SERVER_ADDRESS/vault/vault.sh > "$0"
    ;;
*)
    # Upload a file to the vault
    if [ -z "${1@Q}" ] || [ -z "${2@Q}" ]; then
       echo "Not enough arguments"
       exit 1
    fi
    destination_path="${VAULT_PATH}/$1"
    destination_dir=`dirname "${VAULT_PATH}/$1"`
    ssh -p $PORT ${USER}@${SERVER_ADDRESS} "mkdir -p $destination_dir && exit"
    scp -r -P $PORT "${@:2}" ${USER}@${SERVER_ADDRESS}:"${destination_path}"
    ;;
esac
