diff --git a/mc b/mc index b3ca0b2..25f9977 100755 --- a/mc +++ b/mc @@ -36,8 +36,34 @@ declare -rA commands=( [uninstall]='uninstall POST {"mod": "%s"}' [search]='search POST {"mod": "%s"}' [mod-list]='mod-list GET' + [backup]='backup FUNC' ) +function backup() { + if [[ ! $(which lftp) ]]; then echo "lftp is required"; exit 1; fi + + local sftp_credentials="$(mc my-sftp)" + if [[ "$(jq -r '.success' <<<"${sftp_credentials}" )" != "true" ]]; then + echo "ERROR: failed to get sftp login info"; + exit 1; + fi + + local host="$(jq -r '.hostname' <<<"${sftp_credentials}")" + local username="$(jq -r '.user' <<<"${sftp_credentials}")" + local port="$(jq -r '.port' <<<"${sftp_credentials}")" + local password="$(jq -r '.password' <<<"${sftp_credentials}")" + + local localdir="${MY_MC_BACKUP_DIR:-${HOME}/my-mc_backup/}" + if [[ ! -d ${localdir} ]]; then mkdir -p ${localdir}; exit 1; fi + + pushd "${localdir}" + + lftp -u "${username}","${password}" "${host}":"${port}" -e "set sftp:connect-program 'ssh -o StrictHostKeyChecking=no'; mirror -c --use-pget minecraft/ minecraft/; quit" + + popd +} + + function first() { echo "$@" | cut --delimiter=" " --fields="-1" } @@ -48,18 +74,9 @@ function rest() { fi } -function status_format() { - local tmp=(${1//-/ }) - local second=${tmp[1]} - if [[ "$second" == "sftp" ]]; then - printf "${second^^}" - return - fi - printf "${second^}" -} - function usage() { printf "API key for my-mc must be exported using 'export MY_MC_API_KEY='\n\n" + printf "Backup directory can be changed from default ~/mc-mc_backup/ by using 'export MY_MC_BACKUP_DIR='\n\n" printf "Positional arguments will fill the JSON objects with values from left to right.\n\n" printf "COMMANDS:\n" for command in "${!commands[@]}"; do @@ -68,16 +85,19 @@ function usage() { printf "\n" } - args=("$@") # remove command from arg list while preserving quoted strings. args=("${args[@]:1}") +if [[ ! $(which jq) ]]; then echo "jq is required"; exit 1; fi + for command in "${!commands[@]}"; do if [[ "$1" == "${command}" ]]; then if [[ "$(first $(rest ${commands[$1]}))" == "POST" ]]; then curl -sS "${headers[@]}" -X "$(first $(rest ${commands[$1]}))" "${base_url}$(first "${commands[$1]}")" -d "$(printf "$(rest $(rest ${commands[$1]}))\n" "${args[@]}")" echo "" + elif [[ "$(first $(rest ${commands[$1]}))" == "FUNC" ]]; then + eval "$(first ${commands[$1]})" else curl -sS "${headers[@]}" -X "$(first $(rest ${commands[$1]}))" "${base_url}$(first "${commands[$1]}")" echo ""