#!/usr/bin/perl

use strict;
use warnings;
use FindBin qw( $Bin );
use lib "$Bin/../../lib";
use Data::Dumper;
use App::POS::Config;
use App::POS::Machine::Server;
use UUID::Tiny;
use File::Copy qw( copy );
use POSIX qw( strftime );
use File::Slurp qw( read_dir );

my $clean_customers = shift;

my $force_yes = shift;
$force_yes ||= "";

my $cloud_delete = shift;

if (! $force_yes) {
  print "This will remove ALL the sales, are you sure? [y/n]\n";
  my $ans = <STDIN>;
  chop($ans);
  exit unless uc($ans) eq 'Y';
}
else {
  exit unless $force_yes eq '1';
}

my $cfg = App::POS::Config->new( file => "/opt/pos/etc/config.ini" );
my $info = $cfg->load_fixed();

my $machine = undef;

if (exists $info->{STATION_NUMBER} && $info->{STATION_NUMBER} == 0) {
  $machine = App::POS::Machine::Server->new( config => $cfg );  
} else {
  die "Needs to be executed in the server machine...\n";
}

if (-e "/opt/pos/.hardlock_backups_check") {
  unlink "/opt/pos/.hardlock_backups_check";
}

system("rm -rf /opt/pos/server/data/cashier_open_amount/* 2> /dev/null");
system("rm -f /opt/pos/server/data/database/pos_*.db 2> /dev/null");
system("rm -f /opt/pos/server/data/export/* 2> /dev/null");
system("rm -rf /opt/pos/server/data/opened_cashiers/* 2> /dev/null");
system("rm -rf /opt/pos/server/data/historial_fills/* 2> /dev/null");
system("rm -rf /opt/pos/server/data/stockfiles/* 2> /dev/null");
system("rm -rf /opt/pos/server/data/day_change/* 2> /dev/null");

unlink "/opt/pos/server/data/database/daily_specials_avbl_qtys.ui";
unlink "/opt/pos/server/data/transport_begin.txt";
unlink "/opt/pos/server/data/tmp/money_transit.txt";
unlink "/opt/pos/server/data/products_relevance.txt";

my $db = $machine->database();

$db->do("UPDATE customers SET total_credit = 0, points = 0");

$db->do("TRUNCATE split_docs_link");
$db->do("TRUNCATE counters");
$db->do("TRUNCATE card_sets");
$db->do("TRUNCATE time_clock CASCADE");
$db->do("TRUNCATE transfer_products CASCADE");
$db->do("TRUNCATE transfers CASCADE");
$db->do("TRUNCATE sales_hashes_products CASCADE");
$db->do("TRUNCATE sales_hashes CASCADE");
$db->do("TRUNCATE sales_details_aux CASCADE");
$db->do("TRUNCATE sales_headers_aux CASCADE");
$db->do("TRUNCATE sales_payments_aux CASCADE");
$db->do("TRUNCATE sales_payments CASCADE");
$db->do("TRUNCATE sales_details CASCADE");
$db->do("TRUNCATE sales_details_extra_data CASCADE");
$db->do("TRUNCATE sales_headers CASCADE");
$db->do("TRUNCATE cashdrawer_opens CASCADE");
$db->do("TRUNCATE cashdrawer_operations CASCADE");
$db->do("TRUNCATE vouchers CASCADE");
$db->do("TRUNCATE document_operations CASCADE");
$db->do("TRUNCATE document_history CASCADE");
$db->do("TRUNCATE schedules CASCADE");
$db->do("TRUNCATE cashier_operations CASCADE");
$db->do("TRUNCATE cashiers CASCADE");
$db->do("TRUNCATE stock_movements");
$db->do("TRUNCATE money_counts");
$db->do("TRUNCATE money_counts_operations");
$db->do("TRUNCATE rfid_operations");

if (defined $clean_customers) {
  $db->do("TRUNCATE customers CASCADE");
}

my $recs = $db->select(qq{
  SELECT table_name
  FROM information_schema.tables
  WHERE table_type = 'BASE TABLE' AND table_name LIKE '%_%' AND table_schema = 'public'
});

foreach my $table (@$recs) {
  if ($table->{table_name} =~ /_20/ || $table->{table_name} =~ /_copy/) {
    print STDERR "Will DROP table - ".$table->{table_name}."\n";
    $db->do("DROP TABLE ".$table->{table_name}." CASCADE");
  }
}

system("/opt/pos/server/apps/reinit_tables.pl 2> /dev/null");
system("/etc/init.d/memcached restart 2> /dev/null");

system("ps -eo pid,args | grep \"gbr2 /opt/pos/common/bin/pos\" | grep -v grep | awk '{ print \$1 }' | xargs kill -9 2> /dev/null");
system("ps -eo pid,args | grep \"gbr3 /opt/pos/common/bin/pos\" | grep -v grep | awk '{ print \$1 }' | xargs kill -9 2> /dev/null");
#system("/opt/pos/common/bin/restart_hardware_handler.sh");

# lets create a zip with the files in /opt/backups and cleanup old backups
my @files = read_dir("/opt/backups");

if (scalar @files) {
  my $zip_file = "/opt/backup." . strftime("%Y%m%d_%H%M%S", localtime) . ".zip";
  system("zip -r $zip_file /opt/backups /opt/backups/");
  system("rm -rf /opt/backups/*");
}

if (defined $cloud_delete) {
  if ($cloud_delete eq '1') {
    system("touch /opt/pos/etc/.cloud_backups_cleanup");
  }
}
else {
  my $hardlock = `machine_id 2`;

  if ($hardlock ne '') {
    print STDERR "HARDLOCK: $hardlock\n";

    print "Remove all cloud backups associated with this hardlock? [y/n]\n";
    my $ans = <STDIN>;
    chop($ans);

    if (uc($ans) eq 'Y') {
      system("touch /opt/pos/etc/.cloud_backups_cleanup");
    }
  }
}


