-my %cookie = $query->cookie('userenv');
-($branch) || ( $branch = $cookie{'branch'} );
-($printer) || ( $printer = $cookie{'printer'} );
-
-( $branches->{$branch} ) || ( $branch = ( keys %$branches )[0] );
-( $printers->{$printer} ) || ( $printer = ( keys %$printers )[0] );
-
-# is you force a selection....
-my $oldbranch = $branch;
-my $oldprinter = $printer;
-
-# set up select options....
-my $branchcount = 0;
-my $printercount = 0;
-my @branchloop;
-foreach my $br ( keys %$branches ) {
- next unless $br =~ /\S/; # next unless $br is not blank.
-
- $branchcount++;
- my %branch;
- $branch{selected} = ( $br eq $oldbranch );
- $branch{name} = $branches->{$br}->{'branchname'};
- $branch{value} = $br;
- push( @branchloop, \%branch );
+my $userenv_branch = C4::Context->userenv->{'branch'} || '';
+my $userenv_printer = C4::Context->userenv->{'branchprinter'} || '';
+my @updated;
+
+# $session lddines here are doing the updating
+if ( $branch and my $library = Koha::Libraries->find($branch) ) {
+ if (! $userenv_branch or $userenv_branch ne $branch ) {
+ my $branchname = $library->branchname;
+ $template->param(LoginBranchname => $branchname); # update template for new branch
+ $template->param(LoginBranchcode => $branch); # update template for new branch
+ $session->param('branchname', $branchname); # update sesssion in DB
+ $session->param('branch', $branch); # update sesssion in DB
+ push @updated, {
+ updated_branch => 1,
+ old_branch => $userenv_branch,
+ };
+ } # else branch the same, no update
+} else {
+ $branch = $userenv_branch; # fallback value