#!/bin/bash

#引数のチェック
if [ $# -ne 6 ]; then
#  echo "引数は6つ必要です"
#  echo "第1引数：サーバー"
#  echo "第2引数：ユーザー名"
#  echo "第3引数：パスワード"
#  echo "第4引数：command : get or put"
#  echo "第5引数：ソースファイルパス"
#  echo "第6引数：宛先ファイルパス"

#echo "error"
  exit 1
fi

nServer=$1
nUser=$2
nPass=$3
nCommand=$4
nSrcFilePath=$5
nDestFilePath=$6


if [ ${nCommand} = "get" ]; then
#	echo "---get"
	sFile=`basename ${nSrcFilePath}`
	curl -m 20 -k "sftp://${nServer}${nSrcFilePath}"  -u "${nUser}:${nPass}" -o "${nDestFilePath%/}/${sFile}" --create-dirs
elif [ ${nCommand} = "put" ]; then
#	echo "---put"
	if [ -d $nSrcFilePath ]; then
		exit 1
	fi
	curl -m 20 -k -T "${nSrcFilePath}" -u "${nUser}:${nPass}" "sftp://${nServer}${nDestFilePath%/}/" --ftp-create-dirs
elif [ ${nCommand} = "getall" ]; then
    # 指定フォルダ以下のすべてのファイルをDLする.
    # 一旦ファイルリストを取得してからDL
    nFiles=`curl -m 20 -k -s "sftp://${nServer}${nSrcFilePath%/}/"  -u "${nUser}:${nPass}" | grep -E '^-' | awk '{print $9}'`

    for file in $nFiles
    do
        curl -m 20 -k "sftp://${nServer}${nSrcFilePath%/}/${file}"  -u "${nUser}:${nPass}" -o "${nDestFilePath}/${file}" --create-dirs
    done
else
  exit 1
fi

#正常終了したか
if [ $? -eq 0 ]; then
#	echo "正常終了"
	exit 0
else
#	echo "異常終了"
	exit 1
fi
