# vi: ts=4 expandtab
#
#    Copyright (C) 2014 China Mobile Communications Corporation.
#
#    Author: Hao Li <lihaosz@chinamobile.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License version 3, as
#    published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.


from cloudinit import util

def handle(_name, cfg, cloud, log, args):
    if not cloud.datasource.metadata or 'admin_pass' not in cloud.datasource.metadata:
        log.debug ("admin_pass is not in datasource, could not set root password")
    else:
        admin_pass = cloud.datasource.metadata['admin_pass']
        ch_in = "root:%s\n" % admin_pass
        try:
            log.debug("Changing password for root with admin_pass:")
            util.subp(['chpasswd'], ch_in)
        except:
            util.logexc(log, "Failed to set passwords with chpasswd for root")
