#!/usr/bin/perl 

use Storable;

my $data_file='/home/oc/cd_orders/cd_orders.dat';
my $mailinglist_file='/usr/local/majordomo/lists/cdrom';
my $success_uri='/OIPC/projects/OpenTech/success.shtml';
my $error_uri='/OIPC/projects/OpenTech/error.shtml';

sub Retrieve_Data {
    $hashref = retrieve($data_file);
    %data=%{$hashref};
}

sub Store_Data {
    store(\%data,$data_file);
}

sub Get_Last_ID {
    $maxid=0;
    foreach (@{$data{order}}) {
       $maxid=${%{$_}}{unique_id} if (${%{$_}}{unique_id}>$maxid);
    }
    return $maxid;
}

sub Read_Mailinglist {
    %mailinglist=();
    if (open(FILE,$mailinglist_file)) {
        while($line=<FILE>) {
            $line=~s/\n|\r| +//g;
            $mailinglist{$line}='1';
        }
        close(FILE);
    } else {
        Note("Cannot open mailinglist file: $mailinglist_file");
        Log ("Cannot open mailinglist file: $mailinglist_file");
    }
}

sub Order_Table {
    my ($color1,$color2)=('#d0d0d0','#ccccff');
    Retrieve_Data;
    Read_Mailinglist;
    $BODY.="</center><p>To add new email to cdrom mailing list we have to send email to Majordomo 
    (mailing list program). 
    In the query below you have to type sender's email address. Also result of action is sent back to
    this address and report about new order/request.<p><form action='$self_url'>Email: <input size=30 type=query name=mailsender value='$data{mailsender}'>
    <input type=submit value='Set it'>
    <input type=hidden name=cmd value=order_set_mailsender></form>
    <p>Majordomo will inform person about subscribing to mailing list.
    ";
    $BODY.="<p>Delete doesn't remove subscriber from mailing list!!";
    if (scalar(@{$data{order}})) {
        $BODY.="<p>Click on 'Name' to see order details..<p><center><table width=100%><tr bgcolor=88aaff><td><b>Id</td><td><b>CD Id</td>
        <td><b>Name</td><td><b>Email</td>
        <td><b>Organization</td><td><b>Mailinglist</td><td><b>Delete</b></td></tr>";
        foreach $order (@{$data{order}}) {
            $BODY.="<tr bgcolor=$color1>";
            foreach ('unique_id','id','name','email','organization') {
                if ($_ eq 'name') {
                    $BODY.="<td><a href=$self_url?cmd=order_details&id=${%{$order}}{unique_id}>${%{$order}}{$_}</a></td>";
                } elsif ($_ eq 'email') {
                    $BODY.="<td><a href='mailto\:${%{$order}}{email}'>${%{$order}}{email}</a></td>";
                } else {
                    $BODY.="<td>${%{$order}}{$_}&nbsp;</td>";
                }
            }
            
            if ($mailinglist{${%{$order}}{email}} eq '1') {
                $BODY.="<td><a href=$self_url?cmd=order_ml&action=unsubscribe&id=${%{$order}}{unique_id}>Remove</a></td>";
            } elsif (${%{$order}}{mailinglist} eq '') {
                $BODY.="<td><a href=$self_url?cmd=order_ml&action=subscribe&id=${%{$order}}{unique_id}>Add</a></td>";
            } else {
                $BODY.="<td>${%{$order}}{mailinglist}</td>";
            }
            $BODY.="<td><a href=$self_url?cmd=rm_order&id=${%{$order}}{unique_id}>Delete</a></td>";
            $BODY.="</tr>";
            ($color1,$color2)=($color2,$color1);
        }
        $BODY.="</table>";
    } else {
        $BODY.="<p><b>No orders!</b>";
    }
    $BODY.="<p><form action='$self_url'>Current CD ID: <input type=query name=cd_id value='$data{cd_id}'>
    <input type=submit value='Set it'>
    <input type=hidden name=cmd value=order_set_cd_id></form>";
    $TITLE='OpenTech CDROM orders/requests archive';
    $SELECTED_MENU='inside;order;table';
}

sub Order_Details {
    Retrieve_Data;
    foreach $order (@{$data{order}}) {
        if ($form{id} eq ${%{$order}}{unique_id} &&  ${%{$order}}{id} eq 'add to cd') {
            $BODY="<b>Add design or tool to the cdrom</b><p>";
            $BODY.="<ul>";
            $BODY.="Date: ${%{$order}}{date}<p>";            
            $BODY.="Order id: ${%{$order}}{unique_id}<br>";
            $BODY.="CDROM id: ${%{$order}}{id}<p>";
            $BODY.="Name: ${%{$order}}{name}<br>";
            $BODY.="Email: <a href='mailto:${%{$order}}{email}'>${%{$order}}{email}</a><p>";
            $BODY.="Software/Design name: ${%{$order}}{design}<p>";
            $BODY.="Organization: ${%{$order}}{organization}<p>";
            $tmp=${%{$order}}{description};
            $tmp=~s/\n/<br>/g;
            $BODY.="Description: <br>$tmp<p>";
            $url=${%{$order}}{url};
            $url="http://".$url unless ($url=~m/^http:/i);
            $BODY.="URL: <a target=new href='$url'> ${%{$order}}{url}</a><p>";
            $tmp=${%{$order}}{files};
            $tmp=~s/\n/<br>/g;
            $BODY.="Download file(s): <br>$tmp<p>";
            $tmp=${%{$order}}{comments};
            $tmp=~s/\n/<br>/g;
            $BODY.="Comments: <br>$tmp<p>";
            $BODY.="</ul>";
        } elsif ($form{id} eq ${%{$order}}{unique_id}) {
            $BODY="<b>Order CDROM</b><p>";
            $BODY.="<ul>";
            $BODY.="Date: ${%{$order}}{date}<p>";
            $BODY.="Order id: ${%{$order}}{unique_id}<br>";
            $BODY.="CDROM id: ${%{$order}}{id}<p>";
            $BODY.="Name: ${%{$order}}{name}<br>";
            $BODY.="Email: <a href='mailto:${%{$order}}{email}'>${%{$order}}{email}</a><p>";
            $BODY.="Organization: ${%{$order}}{organization}<p>";
            $tmp=${%{$order}}{address};
            $tmp=~s/\n/<br>/g;
            $BODY.="Address: <br>$tmp<p>";
            $BODY.="City: ${%{$order}}{city}<br>";
            $BODY.="State: ${%{$order}}{state}<br>";
            $BODY.="Zip code: ${%{$order}}{zipcode}<br>";
            $BODY.="Country: ${%{$order}}{country}<p>";

            $BODY.="No. of copies: ${%{$order}}{copies}<br>";

            $url=${%{$order}}{url};
            $url="http://".$url unless ($url=~m/^http:/i);
            $BODY.="URL: <a target=new href='$url'> ${%{$order}}{url}</a><p>";

            $tmp=${%{$order}}{needs};
            $tmp=~s/\n/<br>/g;
            $BODY.="Your needs: <br>$tmp<p>";
            $tmp=${%{$order}}{aboutyou};
            $tmp=~s/\n/<br>/g;
            $BODY.="About you: <br>$tmp<p>";
            $tmp=${%{$order}}{aboutorg};
            $tmp=~s/\n/<br>/g;
            $BODY.="About organization: <br>$tmp<p>";
            $tmp=${%{$order}}{comments};
            $tmp=~s/\n/<br>/g;
            $BODY.="Comments: <br>$tmp<p>";

            $BODY.="</ul>";

        }
    }
    
    $SELECTED_MENU="inside;order";
    $TITLE="Order details";
}

sub Remove_Order {
    Retrieve_Data;
    %new_data=();
    foreach (keys %data) {
        if ($_ ne 'order') {
            $new_data{$_}=$data{$_};
        }
    }
    foreach $order (@{$data{order}}) {
        if ($form{id} ne ${%{$order}}{unique_id}) {
            push(@{$new_data{order}},\%{$order});
        }
    }
    %data=%new_data;
    Store_Data;
    Order_Table;
}

sub Set_Cd_ID {
    Retrieve_Data;
    if ($form{cd_id}=~m/^[0-9]+$/) {
        $data{cd_id}=$form{cd_id};
    } else {
        Note("Incorrect CD Id!");
    }
    Store_Data;
    Order_Table;
}

sub Set_Mailsender {
    Retrieve_Data;
    if ($form{mailsender}=~m/\@/) {
        $data{mailsender}=$form{mailsender};
    } else {
        Note("Incorrect email address: $form{mailsender}");
    }
    Store_Data;
    Order_Table;
}

sub Mailinglist {
    Retrieve_Data;
    foreach $order (@{$data{order}}) {
        if ($form{id} eq ${%{$order}}{unique_id}) {
            if ($form{action} eq 'subscribe') {
                ${%{$order}}{mailinglist}='pending';
            } else {
                ${%{$order}}{mailinglist}='';
            }
            my $sender = new Mail::Sender {
                smtp => 'localhost',
                from => "$data{mailsender}",
                to   => "majordomo\@opencores.org",
                subject => "$form{action} ${%{$order}}{email} - cdrom mailing list",
            };
            $sender->MailMsg({
                msg => "approve secretpassword $form{action} cdrom ${%{$order}}{email}"
            });
            Note($Mail::Sender::Error) if ($Mail::Sender::Error);
        }
    }
    Store_Data;
    Note("Mail was sent to Majordomo.. email should be $form{action}d in a few minutes");
    Order_Table;
}

sub Add_Menu {
    my @tmp_menu=@COMMAND_MENU;
    @COMMAND_MENU=();

    foreach (@tmp_menu) {
        push(@COMMAND_MENU,$_);
        if (${$_}{name} eq 'inside;account') {

            my %item=();
            $item{name}='inside;order;table';
            $item{display}='Orders/Requests';
            $item{link}="$self_url?cmd=order_table";
            push(@COMMAND_MENU,\%item);

            my %item=();
            $item{name}='inside;order;refresh';
            $item{display}='Refresh table';
            $item{link}="$self_url?cmd=order_table";
            push(@COMMAND_MENU,\%item);

            my %item=();
            $item{name}='inside;order';
            $item{display}='OpenTech';
            $item{link}="$self_url?cmd=order_table";
            push(@COMMAND_MENU,\%item);
        }
    }
}



sub Add_Order {
    Retrieve_Data;
    $id=Get_Last_ID;
    $id++;
    %order=();
    if ($form{id} eq 'add to cd') {
        if ($form{name} eq '' 
            || !($form{email}=~m/\@/)
            || $form{design} eq ''
            || $form{description} eq ''
            || $form{url} eq ''
            || $form{files} eq ''
            ) {
            print "Location: $error_uri\n\n";
            exit;
        }
        foreach (id,name,email,design,organization,
          description,url,files,comments) {
            $order{$_}=$form{$_};
        }
    } else {
        if ($form{name} eq '' 
            || !($form{email}=~m/\@/)
            || $form{address} eq ''
            || $form{city} eq ''
            || $form{copies} eq ''
            || $form{country} eq ''
            ) {
            print "Location: $error_uri\n\n";
            exit;
        }
        foreach (id,name,email,organization,address,city,state,zipcode,country,
          copies,url,needs,aboutyou,aboutorg,comments) {
            $order{$_}=$form{$_};
        }
    }
    $order{unique_id}=$id;
    $order{date}=`date`;
    $order{mailinglist}='';
    push(@{$data{order}},\%order);
    Store_Data;
    use Mail::Sender;
    my $sender = new Mail::Sender {
        smtp => 'localhost',
        from => "$data{mailsender}",
        to   => "$data{mailsender}",
        subject => "New order/request for OpenTech CDROM",
    };

    $msg='Error.. please report this to mlampret@opencores.org';
    if ($order{id} eq 'add to cd') {
            $desc=$order{description};
            $desc=~s/\n/\n    /g;
            $files=$order{files};
            $files=~s/\n/\n    /g;
            $comments=$order{comments};
            $comments=~s/\n/\n    /g;

            $msg="
Add design or tool to the cdrom

  Date: $order{date}

  Order id: $order{unique_id}
  CDROM id: $order{id}

  Name: $order{name}
  Email: $order{email}

  Software/Design name: $order{design}
  Organization: $order{organization}

  Description: 
    $desc
           
  URL: $order{url}

  Download file(s): 
     $files

  Comments: 
     $comments

";
        } else {
            $address=$order{address};
            $address=~s/\n/\n    /g;
            $needs=$order{needs};
            $needs=~s/\n/\n    /g;
            $aboutyou=$order{aboutyou};
            $aboutyou=~s/\n/\n    /g;
            $aboutorg=$order{aboutorg};
            $aboutorg=~s/\n/\n    /g;
            $comments=$order{comments};
            $comments=~s/\n/\n    /g;

            $msg="
Order CDROM
            
  Date: $order{date}

  Order id: $order{unique_id}
  CDROM id: $order{id}

  Name: $order{name}
  Email: $order{email}
  Organization: $order{organization}

  Address:
    $address
  
  City: $order{city}
  State: $order{state}
  Zip code: $order{zipcode}
  Country: $order{country}

  No. of copies: $order{copies}

  URL: $order{url}

  Your needs:
    $needs
  
  About you:
    $aboutyou
  
  About organization:
    $aboutorg

  Comments:
    $comments

";
    }


    $sender->MailMsg({
        msg => $msg
    });

    print "Location: $success_uri\n\n";
    exit;
}

if ($USERNAME=~m/khatib|mlampret/) {
    Add_Menu;
    Order_Table if ($form{cmd} eq 'order_table');
    Remove_Order if ($form{cmd} eq 'rm_order');
    Set_Cd_ID if ($form{cmd} eq 'order_set_cd_id');
    Set_Mailsender if ($form{cmd} eq 'order_set_mailsender');
    Order_Details if ($form{cmd} eq 'order_details');
    Mailinglist if ($form{cmd} eq 'order_ml');
}

if ($ENV{SCRIPT_NAME}=~m/order\.cgi$/) {
    use CGI;
    %form=();
    my $query=new CGI;
    foreach ($query->param) {
        $form{$_}=$query->param($_);
    }
    if ($form{cmd} ne 'submit') {
        print "content-type: text/html\n\n";
        Retrieve_Data;
        print "$data{cd_id}";
    } else {
        Add_Order;       
    }
}

1;