#!/usr/bin/perl

use strict;
use warnings;
use Net::OpenSSH;

if ( @ARGV != 5 ) {
	system("pod2usage $0");
	exit(1);
}

my $ipaddr = $ARGV[0];
my $old_username = $ARGV[1];
my $old_password = $ARGV[2];
my $new_username = $ARGV[3];
my $new_password = $ARGV[4];

my $ssh = Net::OpenSSH->new($ipaddr,
            'user' => $old_username,
            'passwd' => $old_password,
            'master_opts' => [
                '-q',
                -o => "UserKnownHostsFile=/dev/null",
                -o => "StrictHostKeyChecking=no"
            ]
);

if ( $ssh->error ) {
	die $ssh->error;
}

my $config = $ssh->capture2('cat','/tmp/system.cfg');

if ( $ssh->error ) {
	die $ssh->error;
}

my $salt;

my $user;
foreach ( split m/\n/,$config ) {
	$user = $1 if m/(users\.\d+)\.name=$old_username/;
}

unless ( $user ) {
	die "$old_username: username not found!";
}

foreach ( split m/\n/,$config ) {
	if ( $_ =~ m/$user.password=(\$1\$\S{8}\$)/ ) {
		$salt = $1;
        last;
    }

	if ( $_ =~ m/$user.password=(..)/ ) {
		$salt = $1;
		last;
	}
}

die "no salt found" unless $salt;

my $old_password_crypted = crypt($old_password,$salt);
my $new_password_crypted = crypt($new_password,$salt);

$old_password_crypted =~ s!/!\\/!;
$new_password_crypted =~ s!/!\\/!;

$ssh->capture2("sed -e 's/$user.password=$old_password_crypted/$user.password=$new_password_crypted/' -e 's/$user.name=$old_username/$user.name=$new_username/' -i /tmp/system.cfg;cfgmtd -w;reboot");

if ( $ssh->error ) {
	die $ssh->error;
}

exit;

__END__

=pod

=head1 NAME

chpasswd-ubiquiti.pl v1.0

=head1 SYNOPSIS

chpasswd-ubiquiti.pl <ipaddr> <old_username> <old_password> <new_username> <new_password>

=head1 DESCRIPTION

skrypt do zmiany loginu/hasła na urządzeniach Ubiquiti

=head1 AUTHOR

mindc.net

=cut