#!/usr/bin/perl

# Copyright (C) 2015 Red Hat
# Copyright (C) 2015-2020 SUSE LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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/>.

use strict;
use warnings;

use FindBin qw($RealBin);
use lib "$RealBin/../lib";

use OpenQA::Schema::Result::ApiKeys;
use OpenQA::Schema;
use OpenQA::Utils 'random_hex';
use Getopt::Long;

my $email    = 'admin@example.com';
my $nickname = 'admin';
my $fullname = 'Administrator';
my $key      = "";
my $secret   = "";
my $user     = $ARGV[0];
my $help;

sub usage {
    print "Usage: $0 [options] user \n\n";
    print "  --email     : Email address.\n";
    print "  --nickname  : Nickname.\n";
    print "  --fullname  : Full name.\n";
    print "  --key       : API key (will be randomly generated if not set).\n";
    print "  --secret    : API secret (will be randomly generated if not set).\n";
    print "  user        : User ID (e.g. OpenID URL).\n";
    print "usage: $_[0]\n";
    exit $_[0];
}

# need to count this *before* calling GetOptions
my $numargs = scalar @ARGV;

my $result = GetOptions(
    "email=s"    => \$email,
    "nickname=s" => \$nickname,
    "fullname=s" => \$fullname,
    "key=s"      => \$key,
    "secret=s"   => \$secret,
    "help"       => \$help,
);

usage 0 if $help;
usage 1 unless $result && $user && $numargs > 1;

if (($key || $secret)
    && !($key =~ /^[[:xdigit:]]{16}$/ && $secret =~ /^[[:xdigit:]]{16}$/))
{
    die "--key and --secret must both be 16 digit hexadecimals.\n";
}

unless ($key) {
    $key    = random_hex();
    $secret = random_hex();
    print "Key: $key\n";
    print "Secret: $secret\n";
}

my $schema = OpenQA::Schema->singleton;
my $users  = $schema->resultset('Users')->find({is_admin => 1});
if ($users != 0) {
    warn "An admin user already exists! Use client or web UI to create further users.\n";
    exit 1;
}
my $account = $schema->resultset('Users')->create_user(
    $user,
    email    => $email,
    nickname => $nickname,
    fullname => $fullname,
    is_admin => 1
);

$schema->resultset("ApiKeys")->create({user_id => $account->id, key => $key, secret => $secret});

