#!/opt/bin/python3
# Changes the password for Deluge's Web UI
# taken from http://dev.deluge-torrent.org/wiki/Faq#HowcanIresetthepassword
# and rewritten to Python 3

from deluge.config import Config
import hashlib
import os
import sys

if len(sys.argv) == 2:
    deluge_dir = os.path.expanduser(sys.argv[1])

    if os.path.isdir(deluge_dir):
        try:
            config = Config("web.conf", config_dir=deluge_dir)
            if 'pwd_salt' not in config:
                raise IOError("Bad config: can't find pwd_salt")
            password = input("Enter new password: ").encode()
            s = hashlib.sha1()
            s.update(config['pwd_salt'].encode())
            s.update(password)
            config['pwd_sha1'] = s.hexdigest()
            try:
                config.save()
            except IOError as e:
                print("Couldn't save new password:", e)
            else:
                print("New password successfully set!")
        except Exception as e:
            print("Exception occured:", e)
    else:
        print("%s is not a directory!" % deluge_dir)
else:
    print("Usage: %s <deluge config dir>" % (os.path.basename(sys.argv[0])))
