use strict;

return sub
{
	my $dbh = shift;


	my $packPasswd = sub
	{
		my $unpackedPasswd = shift;
				
		my $len = length($unpackedPasswd);		
		my $packedPasswd;
		
		$packedPasswd .= $len > 9 ? "$len" : "0$len";
		$packedPasswd .= unpack("H*", $unpackedPasswd);
		
		my @random;
		$len = 32 - length($packedPasswd);
	
		for (my $i = 0; $i < $len; $i++)
		{
			my $rand = int(rand(16));
			my $char = $rand > 9 ? chr(ord('a') + $rand - 10) : chr(ord('0') + $rand);
		
			push @random, $char;
		}
	
		$packedPasswd .= join('', @random);
		$packedPasswd;
	};
	
	my $sth = $dbh->prepare("select id, passwd from jin_user");
	$sth->execute;
	
	my $sthi = $dbh->prepare("update jin_user set passwd=? where id=?");
	
	while (my $row = $sth->fetchrow_hashref)
	{
		my $passwd = $row->{passwd};
		
		next
			if length($passwd) >= 32 && $passwd =~ /^[\dabcdef]+$/;
			
		$sthi->execute(&$packPasswd($passwd), $row->{id});
	}
	

	if (! $dbh->selectrow_array("select count(distinct pack_id) from jin_package_product pp left join jin_package p on p.id=pp.pack_id where p.type=3"))
	{
		my $sth = $dbh->prepare("select * from jin_shopcart_category where prod_list<>''");
		$sth->execute;
		
		my %shopcarts_prods;
		
		while (my $cat = $sth->fetchrow_hashref)
		{
			my @prods;
			
			if ($cat->{prod_sort} eq 'list_asc')
			{
				@prods = split ',', $cat->{prod_list};
			}
			elsif ($cat->{prod_sort} eq 'list_desc')
			{
				@prods = reverse split ',', $cat->{prod_list};
			}
			elsif ($cat->{prod_sort} eq 'title_asc')
			{
				@prods = map { $_->[0] } @{$dbh->selectall_arrayref("select id from jin_product where find_in_set(id,'$cat->{prod_list}') order by title asc")};
			}
			elsif ($cat->{prod_sort} eq 'title_desc')
			{
				@prods = map { $_->[0] } @{$dbh->selectall_arrayref("select id from jin_product where find_in_set(id,'$cat->{prod_list}') order by title desc")};
			}
			elsif ($cat->{prod_sort} eq 'id_asc')
			{
				@prods = sort split ',', $cat->{prod_list};
			}
			elsif ($cat->{prod_sort} eq 'id_desc')
			{
				@prods = reverse sort split ',', $cat->{prod_list};
			}
			else
			{
				@prods = split ',', $cat->{prod_list};
			}
			
			my $i = -1;
			for my $prod_id (@prods)
			{
				$i++;
				$dbh->do("insert into jin_package_product set prod_id=?, pack_id=?, cat_id=?, tstamp=date_add(now(),interval $i second)", undef, $prod_id, $cat->{pack_id}, $cat->{id});
				$shopcarts_prods{$prod_id} = 1;
			}
		}
		
		$dbh->do("update jin_product set shopcart_enabled=1 where find_in_set(id,'".join(',', keys %shopcarts_prods)."')");
	}
	
	return;
};
