#!/usr/bin/env bash
#
# One-time Google Drive login for a server without a browser.
# Run on a desktop that has a browser and Docker. It logs in with your own
# OAuth client and the drive.file scope, copies the rclone config to the
# server, and checks the connection from there. The token is never printed
# and no copy stays on the desktop.
#
# Usage:
#   export GDRIVE_CLIENT_ID=...  GDRIVE_CLIENT_SECRET=...
#   ./gdrive-auth.sh user@server
#
# From: https://jamongx.com/rclone-google-drive-backup-docker/
set -euo pipefail

REMOTE=${1:?usage: ./gdrive-auth.sh user@server}
RCLONE_IMAGE=${RCLONE_IMAGE:-rclone/rclone:1.76.0}   # use the same tag on the server
NAME=${NAME:-gdrive}
: "${GDRIVE_CLIENT_ID:?export GDRIVE_CLIENT_ID first (your own OAuth client)}"
: "${GDRIVE_CLIENT_SECRET:?export GDRIVE_CLIENT_SECRET first}"

# Never overwrite a working token on the server.
ssh "$REMOTE" 'test ! -e ~/.config/rclone/rclone.conf' \
  || { echo "The server already has ~/.config/rclone/rclone.conf. Not overwriting it." >&2; exit 1; }

# Log in into a temp folder that is shredded when this script exits, even on failure.
work=$(mktemp -d)
trap 'find "$work" -type f -exec shred -u {} + 2>/dev/null || true; rm -rf "$work"' EXIT

echo "Open the http://127.0.0.1:53682/auth... link below in this machine's browser, then log in and approve."
# stdout carries the finished config (with the token), so drop it. The login link goes to stderr.
# --network host: Google sends the browser back to 127.0.0.1:53682 on this machine.
docker run --rm --network host --user "$(id -u):$(id -g)" -v "$work":/config/rclone "$RCLONE_IMAGE" \
  config create "$NAME" drive scope=drive.file \
  client_id="$GDRIVE_CLIENT_ID" client_secret="$GDRIVE_CLIENT_SECRET" >/dev/null
grep -q '^token = ' "$work/rclone.conf" || { echo "Login did not finish (no token)." >&2; exit 1; }

# Copy the config to the server, readable only by your user.
ssh "$REMOTE" 'mkdir -p ~/.config/rclone && chmod 700 ~/.config/rclone && umask 077 && cat > ~/.config/rclone/rclone.conf' \
  < "$work/rclone.conf"

# Check the connection from the server.
ssh "$REMOTE" "docker run --rm --user \$(id -u):\$(id -g) -v ~/.config/rclone:/config/rclone $RCLONE_IMAGE about $NAME: >/dev/null" \
  && echo "OK: the server can reach Google Drive." \
  || { echo "The server could not reach Google Drive." >&2; exit 1; }
