#!/bin/sh
# Change the password of an EXISTING FTP account (everything else of the account stays as it is).
#
#   ./set-ftp-password.sh <ftp-user> [password]
#   e.g. ./set-ftp-password.sh meeconic-escudier
#
# Without a password a short, camera-friendly one is generated (same rule as create-ftp-user.sh) and printed once.
# Run on the server, in this folder (it reads .env). Needs curl.
set -eu
cd "$(dirname "$0")"
[ -f .env ] || { echo "No .env here: copy .env.example to .env first."; exit 1; }
set -a; . ./.env; set +a

USER_NAME="${1:?usage: $0 <ftp-user> [password]}"
PASS="${2:-$(LC_ALL=C tr -dc 'abcdefghjkmnpqrstuvwxyz23456789' </dev/urandom | head -c 12)}"
API=http://127.0.0.1:8080/api/v2

case "$PASS" in *[\"\]*) echo "the password may not contain \" or \\"; exit 1;; esac

TOKEN=$(curl -fsS -u "${SFTPGO_ADMIN_USER:-admin}:$SFTPGO_ADMIN_PASSWORD" "$API/token" | sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p')
[ -n "$TOKEN" ] || { echo "Could not log in to SFTPGo (is it running? admin password right?)"; exit 1; }

# SFTPGo replaces the whole account on PUT: send back exactly what it has, plus the new password as the LAST
# key (a JSON decoder keeps the last one if the answer already carried an empty "password").
CURRENT=$(curl -fsS "$API/users/$USER_NAME" -H "Authorization: Bearer $TOKEN") \
  || { echo "No FTP account named $USER_NAME"; exit 1; }
printf '%s,"password":"%s"}' "${CURRENT%\}*}" "$PASS" > /tmp/.ftpuser.$$     # only the LAST "}" goes
curl -fsS -X PUT "$API/users/$USER_NAME" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  --data-binary @/tmp/.ftpuser.$$ >/dev/null || { rm -f /tmp/.ftpuser.$$; echo "SFTPGo refused the change"; exit 1; }
rm -f /tmp/.ftpuser.$$

echo "New password of $USER_NAME (set it in the camera): $PASS"
