#!/usr/bin/perl
use strict;
use warnings;
use Socialtext::Resting;
use Socialtext::EditPage;
use Getopt::Long;

my $rc_file = "$ENV{HOME}/.wikeditrc";
my %opts = load_config($rc_file);

GetOptions(
    'username|u=s' => \$opts{username},
    'password|p=s' => \$opts{password},
    'server|s=s'   => \$opts{server},
    'workspace|w=s'=> \$opts{workspace},
) or usage();

my $page_name = shift || usage();

my $rester = Socialtext::Resting->new(%opts);
my $edit = Socialtext::EditPage->new(rester => $rester);
if ($edit->edit_page(page => $page_name)) {
    print "Updated page $page_name\n";
}
else {
    print "$page_name did not change.\n";
}
exit;


sub usage {
    die <<EOT;
$0 page_name

Options:
 --username     Specify the username to connect with
 --password     Specify the password to connect with
 --server       Which Socialtext server to connect to
 --workspace    Which workspace to post to

Config:
Put the above options into $rc_file like this:

  username = some_user\@foobar.com
  password = your_pass
  workpace = corp
  server   = https://www2.socialtext.net/
EOT
}

sub load_config {
    my $file = shift;

    my %opts;
    if (-e $file) {
        open(my $fh, $file) or die "Can't open $file: $!";
        while(<$fh>) {
            if (/^(\w+)\s*=\s*(\S+)\s*$/) {
                $opts{$1} = $2;
            }
        }
        close $fh;
    }
    return %opts;
}

