#!/bin/bash

# Usage: ./odoo_passwd.sh <container_name>

CONTAINER=$1

if [ -z "$CONTAINER" ]; then
  echo "Usage: $0 <docker_container>"
  exit 1
fi

# Step 1: Get users list
echo "Fetching users..."

USERS=$(doas docker exec -i "$CONTAINER" bash -c \
'PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USER" -At -F"," -c "SELECT id, login FROM res_users ORDER BY id;"')

# Step 2: Display users
echo "Select a user:"
IFS=$'\n'
select USER_LINE in $USERS; do
  if [ -n "$USER_LINE" ]; then
    break
  fi
done

USER_ID=$(echo "$USER_LINE" | cut -d',' -f1)
USER_LOGIN=$(echo "$USER_LINE" | cut -d',' -f2)

echo "Selected user: $USER_LOGIN (ID: $USER_ID)"

# Step 3: Ask for new password
read -s -p "Enter new password: " NEW_PASS
echo
read -s -p "Confirm password: " CONFIRM_PASS
echo

if [ "$NEW_PASS" != "$CONFIRM_PASS" ]; then
  echo "Passwords do not match!"
  exit 1
fi

# Step 4: Generate Odoo-compatible hash using Python inside container
HASH=$(doas docker exec -i "$CONTAINER" python3 - <<EOF
from passlib.context import CryptContext
ctx = CryptContext(schemes=['pbkdf2_sha512'])
print(ctx.hash("$NEW_PASS"))
EOF
)

echo "Updating password..."

# Step 5: Update DB
doas docker exec -i "$CONTAINER" bash -c \
"PGPASSWORD=\"$PASSWORD\" psql -h \"$HOST\" -U \"$USER\" -c \"UPDATE res_users SET password='$HASH' WHERE id=$USER_ID;\""

echo "Password updated successfully for $USER_LOGIN"
