Add page numbers opp. bound edge w/ Postscript/Ghostscript

I need to add page numbers to a 2,000+ page PDF that is already setup for binding. The PDF has extra margin on right and left-hand pages to accommodate the binding.

I found a solution from Brian M. Hunt that places the page number in the same position. I need to modify the code to make the page number position conditional, so that right-hand pages have the number near the right edge and left-hand pages have the number near the left edge.

gs \
  -dBATCH -dNOPAUSE \
  -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress \
  -sOutputFile=/path/to/merged.pdf \
  -c 'globaldict /MyPageCount 1 put << /EndPage {exch pop 0 eq dup {/Helvetica 12 selectfont MyPageCount =string cvs dup stringwidth pop currentpagedevice /PageSize get 0 get exch sub 20 sub 20 moveto show globaldict /MyPageCount MyPageCount 1 add put } if } bind >> setpagedevice'
  -f input1.pdf -f input2.pdf

I need to modify the code to conditionally change the page number position, so that right-hand pages have the number near the right edge and left-hand pages have the number near the left edge.

Here is the modified code to conditionally change the page number position for right-hand and left-hand pages:

gs \
  -dBATCH -dNOPAUSE \
  -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress \
  -sOutputFile=/path/to/merged.pdf \
  -c 'globaldict /MyPageCount 1 put << /EndPage {exch pop 0 eq dup {/Helvetica 12 selectfont MyPageCount =string cvs dup stringwidth pop currentpagedevice /PageSize get exch 2 div get exch sub 20 sub dup 0 lt {pop 20} if 20 gt {pop currentpagedevice /PageSize get exch 0 get sub 20} if moveto show globaldict /MyPageCount MyPageCount 1 add put } {/Helvetica 12 selectfont MyPageCount =string cvs dup stringwidth pop currentpagedevice /PageSize get exch 0 get sub 20 sub dup 0 lt {pop 20} if 20 gt {pop currentpagedevice /PageSize get exch 1 get sub 20} if moveto show globaldict /MyPageCount MyPageCount 1 add put } ifelse } bind >> setpagedevice'
  -f input1.pdf -f input2.pdf

This modified code uses the ifelse statement to determine whether a page is a right-hand page or a left-hand page. For right-hand pages, the page number is positioned near the right edge, and for left-hand pages, it is positioned near the left edge. The moveto command is used to position the page number based on the page orientation.