#!/usr/local/bin/perl
# Config

$version = "3.7";
$base_dir = $ENV{"HOME"}."/back_downloader";
$db_file = "$base_dir/bckdl.db";
$dl_dir = "/stock/download/back_downloader/";
$db_source = $dl_dir."_src";
$log_file = $base_dir."/bckdl.log";
$py_bin = "/home/algalord/.local/bin/pydebrid";


$verbose = 0;
$daemon_interval = 12; # in seconds
#######################################
# back_downloader
#######################################
# Future :
#	Config file
#	Build-in downloader
# 3.7 : jdownloader also used for alldebrid
# 3.5 : add jdownloader warper k2s df
# 3.3.1 : same for ad with _adenable
# 3.3 :
#		enable k2s links by creating a file _k2senable in download dir
# 3.2 :
#		Add plowdown for k2s
# 3.1 :
#		Multidepth destination directory
# 3.0 :
#		Check pydebrid login
#		Deamon Mode
# 2.7 :
# Add add command (or -a) to add a single link
# 2.6 :
# Add : Priority system, new db field <prioriti>, default : 3
#		 0 :  exceptional, 1 : very high, 2 : high, 3 : normal, 4 : low, 5 : very low
#		 priority=# or p=# in source file to set priority
#		 priority <id> # or p <id> # set priority command
#		 priority <id-id> # or p <id-id> # set priority command
# 2.5.2 : 
# Add : command shortcuts
# 2.5.1 : 
# Fix : display help on unkown command
# 2.5 :
# Add : check internet connectivity before downloading	
# 2.4 :
# Add : range for remove/reset/dl params
# Add : change from single file source to directory source
#		 	- _dl.txt in directory source normaly parsed
#			- other .txt files use filename for base destination, unless specified by dest param
# Add : d= in sources files, shorcut for dest=param
# 2.3 :
# Added : delete incomplete files on failure
# Change : full download loop use the download subroutine, means remove duplicate code
# Change : download logs id first, easier reading of logs expected
# 2.2.2
# Fix : check if directory is writable when it exists
# Fix : ignore if source file does not exists
# 2.2
# Change : handle HUP in addition to TERM signal
# Add : new command run_bg and dl_bg, do the same as the old command
#	    but as a daemon. 
# Add : source file can include an optional dest= parameter
#		links following this parameter will go to the >dest< subdirectory of >dl_dir<
# 2.1
# Add : handle TERM (kill) signal to exit
#  
# 2.0
# Add : arguments to control how it works
#  help : display help
#  import : only import links into database
#  list : list links to be downloaded
#  list_run : list currently running downloads
#  list_failed : list failed downloads
#  list_all : list all links (including already downloaded)
#  reset_failed : reset failed downloads to a new attemp
#  reset <id> : reset download with id <id>
#  remove_failed : remove all failed downloads
#  remove <id> : remove link with id <id> from database
#  dl <id> : download link with id <id>
#
# Change : downloaded flag 2 -> means files is currently being downloaded
# Change : downloaded flag 3 means failed download
# Change : main downloading loop query db after every download, with previous change this means 
#          multiple instances can run at the same time
##############################


use Capture::Tiny ':all';
use Switch;
use DBI;
use Proc::Daemon;
use Net::Ping;
use File::Path qw(make_path);

###########################
# Handle Term signal
my $ExitFlag=0;
$SIG{HUP} = $SIG{TERM}  = $SIG{INT} = sub{ logit("TERM signal received"); $ExitFlag = 1 };

my @priorities = ('Exceptional', 'Very High', 'High', 'Normal', 'Low', 'Very Low');

if (($#ARGV > -1)) {
	my $param = $ARGV[1];
	$param =~ /^(\d+)(-*)(\d*)$/;
	my $id = $1 + 0;
	my $lastId = $3 + 0;
	my $param2 = $ARGV[2];
	switch ($ARGV[0]) {
		case "help" { help();}
		case "-h" { help();}
		
		case "import" { InitDB(); ParseNew(); }
		case "-i" { 
			InitDB();
			ParseNew(); 
			my $pending = CountPending();
			print("  $pending links pending.\n");
		}

		case "checkad" {  $verbose = 1; checkAlldebrid(); exit(); }
		case "-c" {  $verbose = 1 ;checkAlldebrid(); exit();}
		
		case "add" { InitDB(); AddLink($ARGV[1], $ARGV[2], $ARGV[3]); }
		case "-a" { InitDB(); AddLink($ARGV[1], $ARGV[2], $ARGV[3]); }

		case "list" { InitDB(); ListLink(1);}
		case "-l" { InitDB(); ListLink(1);}
		case "list_run" { InitDB(); ListLink(2); }
		case "-lr" { InitDB(); ListLink(2); }
		case "list_failed" { InitDB(); ListLink(3); }
		case "-lf" { InitDB(); ListLink(3); }
		case "list_skip" { InitDB(); ListLink(4); }
		case "-ls" { InitDB(); ListLink(4); }
		case "list_all" { InitDB(); ListLink(0); }
		case "-la" { InitDB(); ListLink(0); }

		case "reset_failed" { InitDB(); ResetLink(0); }
		case "-rf" { InitDB(); ResetLink(0); }
		case "reset_skipped" { InitDB(); ResetLink(-1); }
		case "-rs" { InitDB(); ResetLink(-1); }
		case "reset" { if ($id > 0) { InitDB(); ResetLink($id,$lastId); } else {help();}}
		case "-r" { if ($id > 0) { InitDB(); ResetLink($id,$lastId); } else {help();}}

		case "priority" { if (($id > 0) && ($param2 >=1) && ($param2 <= 5)) { InitDB(); SetPriority($id,$lastId,$param2); } else {help();}}
		case "-p" { if (($id > 0) && ($param2 >=1) && ($param2 <= 5)) { InitDB(); SetPriority($id,$lastId,$param2); } else {help();}}

		
		case "remove_failed" { InitDB(); RemoveLink(0); }
		case "-rmfa" { InitDB(); RemoveLink(0); }
		case "remove_finished" { InitDB(); RemoveLink(-1); }
		case "-rmfi" { InitDB(); RemoveLink(-1); }
		case "remove" { if ($id > 0) { InitDB(); RemoveLink($id,$lastId); } else {help();}}
		case "-rm" { if ($id > 0) { InitDB(); RemoveLink($id,$lastId); } else {help();}}


		case "deamon" { 
			print "Starting v$version Deamon Mode\n";
			$verbose = 1; 
			DeamonMode();
			
		}
		case "-d" { 
			print "Starting v$version Deamon Mode\n";
			$verbose = 1; 
			DeamonMode();
		}
		case "deamon-bg" { 
			print "Starting v$version Deamon Mode to Background\n";
			Proc::Daemon::Init;
			DeamonMode();
			
		}
		case "deamon_bg" { 
			print "Starting v$version Deamon Mode to Background\n";
			Proc::Daemon::Init;
			DeamonMode();
			
		}
		case "-dbg" { 
			print "Starting v$version Deamon Mode to Background\n";
			Proc::Daemon::Init;
			DeamonMode();
		}


		case "run" {$verbose = 1;  InitDB(); ParseNew(); Download(); }
		case "run_bg" { 
			print "Going to background\n"; 
			Proc::Daemon::Init;
			InitDB(); 
			ParseNew(); 
			Download(); 
		}
		case "bg" { 
			print "Going to background\n"; 
			Proc::Daemon::Init;
			InitDB(); 
			ParseNew(); 
			Download(); 
		}
		case "run-bg" { 
			print "Going to background\n"; 
			Proc::Daemon::Init;
			InitDB(); 
			ParseNew(); 
			Download(); 
		}
		case "dl" { if ($id > 0) { InitDB(); Download($id,$lastId); } else {help();}}
		case "dl_bg" { if ($id > 0) {
			print "Going to background\n"; 
			Proc::Daemon::Init;
			InitDB();
			Download($id,$lastId);	
		} else {help();}

		}
		else { help(); }
	}
}
else { #standard behaviour, parse and download files
	## run the parsing routine
	help();
}

$dbh->disconnect();

#############################
# Daemon mode routine
# Loops forever
sub DeamonMode {
	InitDB(); 
	while ($ExitFlag == 0) {
		print(" tic\n");
		ParseNew();	
		$req = "SELECT id FROM download WHERE downloaded=0";
		$res = $dbh->prepare($req);
		$ret = $res->execute();
		if(@row =  $res->fetchrow_array()) {

			Download(); 
		}
		sleep($daemon_interval);
	}
}

#############################
# AddLink routine
# argument :
#  link		link to download
#  dest		dest folder (default none)
#  priority 
sub AddLink {
	 
	my ($link, $destination, $priority) = @_;
	if ($link =~ /^http/) {
			$priority +=0;
			if ($priority < 0 || $priority > 5) { $priority = 3; }
			$req = "INSERT INTO download (link,destination,priority) VALUES ('".$link."','".$destination."',$priority)";
					#print $req."\n";
					if (!$dbh->do($req)) {
						print "Error importing link : $line \n";
					}
					else {
						print "Link added successfully\n";
					}
				}
	else {
		print "Non HTTP link, ignoring.\n";
	}
}


#############################
# ListLink routine
# argument :
#  1 list links to be downloaded (downloaded = 0)
#  2 list links actually downloaded (downloaded = 2)
#  3 list links that failed to be downloaded (downloaded = 3)
#  0 list all links
sub ListLink {
	 
	my ($option) = @_;
	$option += 0;
	my @title = qw(Full Pending Running Failed Skipped);
	print $title[$option]." list of links in database";
	my $req = "SELECT id, link, date, downloaded, destination, priority FROM download";
	my $nb = 0;
	if ($option) { 
		$req .= " WHERE downloaded=";
		if ($option == 1) { $req.="0"; }
		else { $req.="$option"; } 
		print " \n";
	}
	else {
		print "   (P=pending, F=finished, R=running, E=error, S=skip)\nStatus\t";
		}
	$req .= " ORDER BY ";
	if ($option == 1) { $req .= "priority, "; }
	$req .= "date;";
	print "ID\t Date\t\t\tLink\t\t\t\t\Destination\t\tPriority\n";
	$res = $dbh->prepare($req);
	$ret = $res->execute();
	while(@row =  $res->fetchrow_array()) {
		if(!$option) {
			switch($row[3]) { 
				case 0 { print " P\t";}
				case 1 { print "  F\t";}
				case 2 { print "   R\t";}
				case 3 { print "    E\t";}
				case 4 { print "     S\t";}
			}
		}
		print "$row[0]\t$row[2]\t$row[1]\t$row[4]\t$priorities[$row[5]]\n";
		$nb++;
	}
	print "\nTotal : $nb links displayed\n";
}

##################################################
# SetPriority
#  id : 1st ID
#  lastId : if applicable, or 0
#  priority : value 0-5
sub SetPriority{
	my ($id, $lastId, $priority) = @_;
	$id += 0;
	$lastId  += 0;
	$priority +=0 ;
	if ($id && !$lastId) {
		$req = "UPDATE download SET priority=$priority WHERE id=$id";
		$res = $dbh->do ($req);
		if ($res > 0) { print "Priority of $id link set to $priorities[$priority] ($priority)\n"; }
		else { print "Failed to change priority of link !\n"; }		
	}
	elsif ($id && $lastId) {
		$req = "UPDATE download SET priority=$priority WHERE id>=$id AND id <=$lastId";
		$res = $dbh->do ($req);
		if ($res > 0) { print "Priority of $res links set to $priorities[$priority] ($priority)\n"; }
		else { print "Failed to change priority of links !\n"; }		
	}
		
}

##################################################
# ResetLink 
# 0 Reset all failed links
# -1 Reset skipped
# other reset only link with provided id
sub ResetLink{
	my ($id,$lastId) = @_;
	$id +=0;
	$lastId +=0;
	my $req, $res;
	if (!$id) {
		$req = "UPDATE download SET downloaded=0 WHERE downloaded=3";
		$res = $dbh->do ($req);
		print "Changed status of $res links to pending\n";
	}
	elsif($id == -1) {
		$req = "UPDATE download SET downloaded=0 WHERE downloaded=4";
		$res = $dbh->do ($req);
		print "Changed status of $res links to pending\n";		
	}
	elsif ($lastId) {
		$req = "UPDATE download SET downloaded=0 WHERE id>=$id AND id<=$lastId;";
		$res = $dbh->do ($req);
		if ($res > 0) { print "Status of $res links reset successful\n"; }
		else { print "Failed to change status of link !\n"; }		
	}
	
	else {
		$req = "UPDATE download SET downloaded=0 WHERE id=$id;";
		$res = $dbh->do ($req);
		if ($res > 0) { print "Status of link reset successful\n"; }
		else { print "Failed to change status of link with id $id !\n"; }		
	}
}

############################################
# RemoveLink routine
# argument
#  -1 : remove finished links (downloaded =1)
#   0 : remove failed links (downloaded = 3)
#  id : remove link with id <id>
sub RemoveLink {
	my ($id,$lastId) = @_;
	$id +=0;
	$lastId +=0;
	my $req, $res;
	if ($id == 0) {
		$req = "DELETE FROM download WHERE downloaded=3";
		$res = $dbh->do($req);
		print "Removed $res links from database\n";
	}
	elsif ($id == -1) {
		$req = "DELETE FROM download WHERE downloaded=1";
		$res = $dbh->do($req);
		print "Removed $res links from database\n";
	}
	elsif ($id > 0 && $lastId) {
		$req = "DELETE FROM download WHERE id>=$id AND id<=$lastId";
		$res = $dbh->do($req);
		if ($res > 0) {  print "$res Link(s) deleted successfully\n"; }
		else { print "Failed to delete links\n"; }
	}
	elsif ($id > 0) {
		$req = "DELETE FROM download WHERE id=$id";
		$res = $dbh->do($req);
		if ($res > 0) {  print "Link $id deleted successfully\n"; }
		else { print "Failed to delete link with id $id !\n"; }
	}
}

#############################
# Database initialisation
sub InitDB {
	$dbh = DBI->connect("dbi:SQLite:dbname=$db_file","","") or die $DBI::errstr."\n DB file = $db_file";

	my $req = "CREATE TABLE IF NOT EXISTS 'download'(
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		link TEXT,
		date TEXT DEFAULT (datetime('now','localtime')),
		downloaded INTEGER DEFAULT 0,
		destination TEXT DEFAULT '',
		priority INTEGER DEFAULT 3);";

	my $res = $dbh->do($req) or die "Error creating table : $DBI::errstr";
}

############################
# CheckDestination 
#  argument : destination
#   remove non alpha numerique chars from destination
#   create directory if needed
#	return destination name
sub CheckDestination {
	my $fullpath;
	my ($destination) = @_;
	$destination  =~ s/[^a-zA-Z0-9 ._\/-]//g;
	$destination  =~ s/(\.\.\/)]//g;
	$fullpath = $dl_dir."/".$destination;
	#print ("destination : ".$destination."\n");
	if (-d -w $fullpath) { #destination exists, is writable, nothing to do
		return $destination;
	}
	elsif ((-e $fullpath)) { #destination is a file, or non writable directory
		my $i = 1;
		while (!(-d -w $fullpath.".$i") && (-e $fullpath.".$i")) {
			$i++;
		}
		$destination .= ".$i";
	}
	$fullpath = $dl_dir."/".$destination;
	if (!(-d $fullpath)) { #destination not exist, create it
		make_path($fullpath,  {error => \my $err} );
		if ($err && @$err) {
			return "";
		}
	}
	return $destination;
}

##################################
# Download loop
# Argument :
#   none = download all pending links
#	one argument = id to download, should be a pending link
#	two argument = download range of pending links
sub Download {
	#if (!checkAlldebrid()) {   logit("Error : check Alldebrid connexion"); return 0; }
	my ($id,$lastId) = @_;
	$id +=0;
	$lastId +=0;
	if (!$id) {
		logit("Session started : downloading all pending links");
	}
	elsif (!$lastId) {
		logit("Session started : downloading link with id ($id)");
	}
	else {
		logit("Session started : downloading links ($id) to ($lastId)");
	}
	my $finished = 0;
	my $nb_dl = 0;
	my $nb_er = 0;
	$req = "SELECT id, link, date, downloaded, destination FROM download WHERE downloaded=0";
	if ($id && $lastId) { $req .= " AND id>=$id AND id<=$lastId"; }
	elsif ($id) { $req .= " AND id=$id"; }
	$req .= " ORDER BY priority, id LIMIT 1";
	while (!$finished && !$ExitFlag) {
		#	$req = "SELECT id, link, date, downloaded, destination FROM download WHERE downloaded=0 ORDER BY id LIMIT 1";
		$res = $dbh->prepare($req);
		$ret = $res->execute();
		if(@row =  $res->fetchrow_array()) {
			if (DownloadLink($row[0])) {
				$nb_dl++;
			}
			else { 
				$nb_er++;
			}
		}
		else {
			$finished = 1;
		}
		$res->finish();
	}
	if ($ExitFlag) { logit("Interrupted by TERM signal");}
	$endstatement = "Finished ! Succesfully downloaded $nb_dl files, $nb_er failed !\n";
	logit($endstatement);
	#print $endstatement;
}

####################################
# DownloadLink
# argument : id to be downloaded
# return 1 on success, 0 on failure
sub DownloadLink {
	if (!checkInternet()) {   logit("Error : check internet connexion"); sleep(3); return 0; }
	#if (!checkAlldebrid()) {   logit("Error : check Alldebrid connexion"); sleep(3); return 0; }
	my($id) = @_;
	my $req, $res, $ret, $downloadedFile;
	my $success = 0;
	$req = "SELECT id, link, date, downloaded,destination FROM download WHERE id=$id;";
	$res = $dbh->prepare($req);
	$ret = $res->execute();
	if(@row =  $res->fetchrow_array()) {
		$destination = CheckDestination($row[4]);
		
		if ( $row[1] =~ /(keep2share|k2s|k2share|keep2s)\.cc.*/) {
			
			#$cmd = " /usr/bin/plowdown -o '$dl_dir/$destination' $row[1]";
			$cmd = "/usr/local/bin/python2.7 /home/algalord/jd.py '$row[1]' '$dl_dir/$destination'";
			logit($cmd);
			if (k2s_enable() == 0) {
					logit("Skip k2s link");
					$dbh->do("UPDATE download SET downloaded=4 WHERE id=$row[0]");
					next;

			}

		}
		elsif ( $row[1] =~ /(depositfiles|dfiles)\.(com|eu|org).*/) {
			
			#$cmd = " /usr/bin/plowdown -o '$dl_dir/$destination' $row[1]";
			$cmd = "/usr/local/bin/python2.7 /home/algalord/jd.py '$row[1]' '$dl_dir/$destination'";
			if (k2s_enable() == 0) {
					logit("Skip k2s link");
					$dbh->do("UPDATE download SET downloaded=4 WHERE id=$row[0]");
					next;

			}

		}		
		elsif ( $row[1] =~ /fs.*filejoker\.net.*/) {
			$cmd = " /home/algalord/.local/bin/filejokerdl.sh '$row[1]' '$dl_dir/$destination' ";
			print $cmd;
			if (fj_enable() == 0) {
					logit("Skip filejoker link");
					$dbh->do("UPDATE download SET downloaded=4 WHERE id=$row[0]");
					next;

			}

		} 
		else {
			# pydebrid hs .... switch to jdownloader
			
#			$cmd = $py_bin." -u '".$row[1]."' -d -o '$dl_dir/$destination'";
#			if (ad_enable() == 0) {
#					logit("Skip ad link");
#					$dbh->do("UPDATE download SET downloaded=4 WHERE id=$row[0]");
#					next;

#			}
			$cmd = "/usr/local/bin/python2.7 /home/algalord/jd.py '$row[1]' '$dl_dir/$destination'";
			if (ad_enable() == 0) {
					logit("Skip ad link");
					$dbh->do("UPDATE download SET downloaded=4 WHERE id=$row[0]");
					next;

			}
		}
		$dbh->do("UPDATE download SET downloaded=2 WHERE id=$row[0]");
		
		logit("($row[0]) Starting download of $row[1] > $destination");
		#logit($cmd);
		($stdout, $stderr, $returnCode) = capture {
			system($cmd);
		};
		chomp($stdout);
		chomp($stderr);
		if ($stdout ne "") { 
			if ($stdout =~ /^Outputing at: (.*)/) { 
				$downloadedFile = $1;
				logit("($row[0]) Saved to > $downloadedFile");
			}
			else {
				logit("($row[0]) ".$stdout);
			}
		}
		if ($stderr ne "") { logit($stderr);}
		
		if ($returnCode == 0) {
			#set  link as downloaded
			logit("($row[0]) Download complete");
			$dbh->do("UPDATE download SET downloaded=1 WHERE id=$row[0];");
			$success = 1;
		}
		else { 
			$success = 0;
			logit("($row[0]) Error downloading $row[1] ($returnCode)");
			if (-e $downloadedFile) {
				if (unlink($downloadedFile)) { logit("($row[0]) Deleted incomplete $downloadedFile"); }
				else { logit("($row[0]) Error deleting $downloadedFile"); }
			}
			$dbh->do("UPDATE download SET downloaded=3 WHERE id=$row[0];");
		}
		$res->finish();
		return $success;
	}
}

####################################
# Parsing sub : scan source dir and parse files
# _dl.txt file set destination to base dir
# *.txt files set destination to their filename
# dest= or d= line change destination
# files are renamed to .<timename>.timespamp when processed
sub ParseNew {
	
	if (!(-d $db_source)) {
		logit("Parser : Could not find source directory");
		return;
	}
	elsif(!(-r -x $db_source)) {
		logit("Parser : Could not open source directory");
		return;
	}
	
	my $DIR;
	if (opendir($DIR, $db_source)) {
		my @files =  grep {/^[^\.].*(\.txt)$/ && -f "$db_source/$_"} readdir($DIR);
		closedir $DIR;
		
		
		my $added = 0;
		my $destination = "";
		my $priority = 3;
		my $countParsed=0, $curFile="";
		foreach $curFile(@files) {
			$priority = 3; 		# reset priority between files
			if ($curFile eq "_dl.txt") { $destination = ""; logit("Parser : _dl.txt found");}
			else { $curFile =~ /^(.*)(\.txt)$/; $destination = $1; logit("Parser : $curFile found"); }
			my $fhi,$fho;
			if (!open ($fhi, "<:encoding(utf8)", "$db_source/$curFile")) {
				print "Could not open $curFile, file not parsed\n";
				next;
			}
			$added = 0;
			while (my $line = <$fhi>) {
				$oline = $line;
				$line =~ s/\r|\n//g;
				$line =~ /^$/ and next;
				if (($line =~ /^d=(.*)$/i) || ($line =~ /^dest=(.*)$/i)) {
					$destination = $1;
				}
				elsif (($line =~ /^p=([0-5])$/i) || ($line =~ /^priority=([0-5])$/i)) {
					$priority = $1;
				}
				elsif ($line =~ /^http/) {
					$line =~ s/'/''/g ;
					$req = "INSERT INTO download (link,destination,priority) VALUES ('".$line."','".$destination."',$priority)";
					#print $req."\n";
					if (!$dbh->do($req)) {
						print "Error importing link : $line \n";
						print $fho $oline;
					}
					else {
						$added++;
					}
				}
			}
			close($fhi);
			$time = time();
			logit("Parser : Added $added link(s) to download database.");
			if (!rename("$db_source/$curFile","$db_source/.$curFile.$time")) { logit("Parser : WARNING : Could not rename $curFile, file will be parsed again next time"); }
			$countParsed++;
			
		}
		
		if ($countParsed > 0) {
			my $pending = CountPending();
			logit("Parser : $countParsed file(s) parsed");
		}
		else {
			my $pending = CountPending();
			logit("Nothing done, $pending links pending.");
		}
	}
	else { logit("Parser : Error openning source directory "); }
	
	
	return;

	
	my $fhi,$fho;
	if (!open ($fhi, "<:encoding(utf8)", $db_source)) {
		print "Could not open input file\n";
		return;
	}

	if (!open($fho, ">", $db_source.".tmp")) {
		print "Could not open output file\n";
		$dbh->disconnect();
		close ($fhi);
		exit 1;
	}

			my $added = 0;
			my $destination = "";
			while (my $line = <$fhi>) {
				$oline = $line;
				$line =~ s/\r|\n//g;
				$line =~ /^$/ and next;
				if ($line =~ /^dest=(.*)$/i) {
					$destination = $1;
				}
				elsif ($line =~ /^http/) {
					$req = "INSERT INTO download (link,destination) VALUES ('".$line."','".$destination."')";
					#print $req."\n";
					if (!$dbh->do($req)) {
						print "Error importing link : $line \n";
						print $fho $oline;
					}
					else {
						$added++;
					}
				}
			}

	close($fho);
	close($fhi);
	###############################
	# replace source file with new one
	unlink($db_source);
	rename($db_source.".tmp",$db_source);

	logit("Added $added files to download database.");
}
sub CountPending {
	my $req = "SELECT COUNT(id) FROM download  WHERE downloaded=0";
	$res = $dbh->prepare($req);
	$ret = $res->execute();
	while(@row =  $res->fetchrow_array()) {
		$res->finish();
		return $row[0];
	}
	
	return 0;
	
}

sub checkAlldebrid{
	
	$cmd = $py_bin." -i | grep Username";
	($stdout, $stderr, $returnCode) = capture {
		system($cmd);
	};
	if ($returnCode == 0) {
		if (-e "$dl_dir/_BCKDL-AlldebridERROR") {
			unlink "$dl_dir/_BCKDL-AlldebridERROR" or logit("Alldebrid workin, but cannot delete error file");
		}
		return 1;
	}
	else {
		logit("AllDebrid Check : Error");
		open HANDLE, ">>$dl_dir/_BCKDL-AlldebridERROR" or logit("Alldebrid not working, and cannot create file to say it");
		close HANDLE;
		return 0;
	}
	
}

sub k2s_enable{
	if (-e "$dl_dir/_k2senable") {
		return 1;
	}
	else {
		return 0;
	}
	
}

sub fj_enable{
	if (-e "$dl_dir/_fjsenable") {
		return 1;
	}
	else {
		return 0;
	}
	
}

sub ad_enable{
	if (-e "$dl_dir/_adenable") {
		return 1;
	}
	else {
		return 0;
	}
	
}

sub checkInternet{
  my $p=new Net::Ping("tcp",2);
  $p->service_check('1');
  $p->port_number(80);
  my $stop_time = time() + 2;
  my $host = "www.google.com";
  my $return = 0;
  while ($stop_time > time())
    {
#        print "$host not reachable ", scalar(localtime()), "\n"
		$return = $p->ping($host);
        sleep(1)    unless $return ;
    }
    undef($p);
  return $return;
}

###############################
# Logging sub : add timestamp and write message to the log file
sub logit{
    my ($logline) = @_;
    my $log;
    open($log,'>>',$log_file);
    my $date = localtime();
    print $log "$date : $$: $logline\n";
    close ($log);
	if ($verbose) {
		print($logline."\n")
    }
}

##################################
# help : display usage
sub help {
	my $help = qq(Background Downloader $version
	help 			display this help
	
	run			import new links and start the download
	run_bg, bg		same as above, but in background
	import, -i		only import links into database
	
	deamon-bg, -dbg		Start deamon mode in background
	
	checkad				check Alldebrid login
	-c
	
	add <link> [dest] [priority]
	-a  <link> [dest] [priority]
	
	list, -l		list links to be downloaded
	list_run, -lr		list currently running downloads
	list_failed, -lf	list failed downloads
	list_all, -la		list all links (including already downloaded)
	list_skip, -ls		list skipped links
	
	reset_failed, -rf	reset failed downloads to a new attemp
	reset_skipped, -rs	reset skipped downloads
	reset <id>, -r		reset download with id <id>
	reset <id1>-<id2>, -r	reset download with from <id1> to <id2> 
	
	remove_failed,-rmfa	remove all failed downloads
	remove_finished, -rmfi 	remove all finished downloads
	remove <id>, -rm	remove link with id <id> from database
	remove <id1>-<id2>, -rm	remove link from <id1> to <id2> from database

	priority <id> #, -p	set priority of <id> to #
	priority <id>-<id2> #	set priority of <id> to <id2> to #
				 Priority levels 1: very high, 2:high, 
				 3:nornal, 4:low, 5:very low
	
	dl <id>			download link with id <id>
	dl_bg <id>		same as above, but in background
	dl <id1>-<id2>		download link from <id1> to <id2>
	dl_bg <id1>-<id2>	same as above, but in background

Use dest=<dest_dir> in source file to set subdirectory destination
	
If TERM or HUP signal is received during the download loop, application wait the current download to complete before exiting.
);
print $help;
	exit;
}
