#!/bin/sh
# Create the FTP account of a school (or of one photographer of a school) in SFTPGo. Its folder is
# FTP_INCOMING_DIR/{school}/ — exactly the folder the backend's organizer reads for that school.
#
#   ./create-ftp-user.sh <ftp-user> <school-id> [password]
#   e.g. ./create-ftp-user.sh xavier-sanmartin san-martin
#
# <school-id> is the school's id in the Meeconic admin (e.g. "san-martin"). Without a password one is generated
# 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> <school-id> [password]}"
SCHOOL="${2:?usage: $0 <ftp-user> <school-id> [password]}"
# 12 lower-case letters and digits, without the ones a camera keypad makes easy to mix up (0/o, 1/l/i): it is
# typed on the camera (the old 20 mixed-case characters were a pain, 2026-10-20). ~59 bits, and the SFTPGo
# defender (docker-compose.yml) bans an IP after a few wrong guesses; the account can only upload anyway.
PASS="${3:-$(LC_ALL=C tr -dc 'abcdefghjkmnpqrstuvwxyz23456789' </dev/urandom | head -c 12)}"
API=http://127.0.0.1:8080/api/v2

case "$SCHOOL" in *[!a-z0-9-]*|"") echo "school id must be lower-case letters, digits and '-'"; 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; }

# Permissions: list and upload (overwrite/rename for cameras that retry or upload under a temporary name).
# No download, no delete: the account can only drop photos, never read or remove the school's files.
# No create_dirs either: the organizer reads the school folder itself, not sub-folders, so a camera set to make
# folders (DCIM/100NIKON/…) would leave its photos unseen. Refused, the upload fails ON THE CAMERA, where the
# photographer sees it, instead of silently on the server.
curl -fsS -X POST "$API/users" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d @- <<EOF
{
  "status": 1,
  "username": "$USER_NAME",
  "password": "$PASS",
  "home_dir": "/srv/incoming/$SCHOOL",
  "description": "Meeconic camera upload for school $SCHOOL",
  "permissions": {"/": ["list", "upload", "overwrite", "rename"]},
  "filesystem": {"provider": 0}
}
EOF
echo
echo "FTP account created — give these to the photographer / set them in the camera:"
echo "  server:   $FTP_PUBLIC_IP   port ${FTP_PORT:-21} (FTP/FTPS, passive mode)   or SFTP port ${SFTP_PORT:-2022}"
echo "  user:     $USER_NAME"
echo "  password: $PASS"
echo "  folder:   /   (leave empty / root)"
