#!/usr/bin/env python3
import sys
import hashlib

# Extracted salt from router firmware in /bin/mkxqimage
salt = {
    'r1d': 'A2E371B0-B34B-48A5-8C40-A7133F3B5D88',
    'others': 'd44fb0960aa0-a5e6-4a30-250f-6d2df50a'
}

def print_line(message):
    print(message)

def get_passwd(sn):
    # Password algorithm: original SN concatenated with reversed salt, perform md5 operation and take first 8 characters
    return hashlib.md5((sn + get_salt(sn)).encode()).hexdigest()[:8]

def get_salt(sn):
    # If SN does not contain '/', then it's r1d
    if '/' not in sn:
        return salt['r1d']
    else:
        return swap_salt(salt['others'])

def swap_salt(salt):
    # Non-R1D salt needs to be reversed before use
    return '-'.join(reversed(salt.split('-')))

def main():
    print('\nThis script computes the default root password from Xiaomi Router\'s SN\nwhich can be found after logging into the router management page\n')
    if len(sys.argv) != 2:
        print('Usage: {} Your-Router-SN'.format(sys.argv[0]))
        sys.exit(1)

    print_line('Your default password is: ' + get_passwd(sys.argv[1]))

if __name__ == "__main__":
    main()
