#!/usr/bin/python3
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Utility to change user password in FreedomBox's Django database.

Usage:
$ freedombox-change-password <username>
"""

import argparse
import getpass
import sys

import plinth.web_framework
from plinth.modules.users import privileged


def main():
    """Ask for new password, setup Django and update a user's password."""
    try:
        plinth.web_framework.init()
    except Exception:
        _print('Error initializing Django.')
        return

    parser = argparse.ArgumentParser()
    parser.add_argument('username',
                        help='Username of the account to change password for')
    args = parser.parse_args()

    username = args.username
    password = getpass.getpass('Enter new password: ')

    try:
        _change_password(username, password)
        privileged._set_user_password(username, password)
        privileged._set_samba_user(username, password)
        _print('Password updated in web interface, LDAP, and samba databases.')
    except Exception as exception:
        _print('Error setting password:', str(exception))


def _print(*args, **kwargs):
    """Write to stderr."""
    print(*args, **kwargs, file=sys.stderr)


def _change_password(username: str, password: str):
    """Update the password in SQLite database file."""
    from django.contrib.auth.models import User
    try:
        user = User.objects.get(username=username)
        user.set_password(password)
        user.save()
    except User.DoesNotExist:
        _print('User account does not exist:', username)
        raise


if __name__ == '__main__':
    main()
