#!/usr/bin/perl
# SourceForge.JP Wiki manipulator
# by hylom
# This code is under GPL.
#

use warnings;
use strict;

use utf8;
use open IO => ':utf8';
use open ':std';

# 下記は環境に応じて適当に変更
# Otp.pm およびOtpディレクトリ（Otp/Attach.pm）があるディレクトリを指定する
# use lib '~/bin'
use lib 'C:\Users\hirom\bin\otptools';

use Otp;
use IO::File;
use Term::Prompt;
use URI::Escape;
use Encode;
use File::Temp;
use Getopt::Std;

my $usage = <<EOD;
otp_attach.pl file 

example:
    otp_attach.pl login -u loginname -p password
    otp_attach.pl logout
    otp_attach.pl attach -i sid -f attachmentfile
EOD

my $command = shift @ARGV;
unless( $command ) {
  print $usage;
  exit;
}

if ( $command eq 'login' ) {	#login
  my %opts;
  getopt('up', \%opts);
  my $login_name;
  my $password;

  if ( defined $opts{'u'} ) {
	$login_name = $opts{'u'};
  } else {
	$login_name = prompt( 'x', 'loginname:', '', '' );
  }

  if ( defined $opts{'p'} ) {
	$password = $opts{'p'};
  } else {
	$password = prompt( 'p', 'password:', '', '' );
	print "\n";
  }

  print "do login...\n";
  login( $login_name, $password);

} elsif ( $command eq 'attach' ) { #attach
  my %opts;
  getopt('if', \%opts);

  my $sid = $opts{'i'};
  my $file = $opts{'f'};
  add_attachment( $sid, $file );

} elsif ( $command eq 'logout' ) { #logout
  print "do logout...\n";
  logout();

} else {						#other
  print $usage;
  exit;
}

sub login {
  my $login_name = shift @_;
  my $password = shift @_;

  my $otp = Otp->new();
  $otp->login( $login_name, $password );
}

sub logout {
  my $otp = Otp->new();
  $otp->logout();
}

sub add_attachment {
  my $sid = shift @_;
  my $file = shift @_;

  if ( ! -e $file ) {
	die "$file is not exist.\n";
  }

  my $otp = Otp->new();
  my $ret = $otp->Attach->post_attachment( sid => $sid,
										  file => $file );

  if ( $ret ) {
	print "$file: upload succeed.\n";
  } else {
	print "$file: upload failed.\n";
  }
}

