Five balls later Pakistan were shell-shocked, the scoreboard remarkably reading 14 for three, as Murtagh took his second wicket of the day with the Ireland strike bowler sending an absolute corker down the track and straight through between bat and off stump, as Asad Shafiq was out for a solitary run.
Imam shared a vital 126-run stand with Babar Azam (59) for the fourth wicket.
This was O'Brien's first global century since he scored the fastest-ever World Cup hundred, off just 50 balls, in Ireland's stunning win over England at Bangalore seven years ago.
It took just four deliveries as Azhar Ali, who had been dancing down the wicket in a bid to put the Middlesex bowler out of his rhythm, nicked off to first slip where Paul Stirling took the catch.
Before this match, Amir had taken 95 wickets in 30 Tests and last season he helped Essex win English cricket's first-class County Championship.
"They have a quality line-up but if we had got another couple and break that partnership, then it's completely game on", added Porterfield, reflecting on the missed opportunity to cause another major shock in world cricket.
Although the crowd was small at that stage of the morning, Ireland's supporters were making plenty of noise as Tim Murtagh took the new ball from the Dublin Road end, tasked with getting among the Pakistan top order.
The 11th Test nation's optimism began to dissipate with Imam and Azam at the crease, though the former was fortunate an edge dropped short off Murtagh and the latter was nearly undone by a Rankin yorker.
Pakistan now heads to England for a two-test series, starting next week at Lord's.
Imam continued his impressive display hitting the half-century mark in his test maiden, propelling Pakistan to 93-3 - leaving 67 for the win.
The two sides posed together soon after for a photograph to mark the historic occasion, while Kevin O'Brien was awarded the man of the match award for his second-innings heroics with the bat.
It was just after 6.15pm that Kevin O'Brien pushed a ball from Mohammad Amir through the covers for runs that made him a national cricketing hero, for the second time in his career.
Pakistan bowling coach Azhar Mahmood suggested after stumps on Sunday that Amir's lengthy time away from the game allied to the fact he had been involved in all three global formats-Tests, one-dayers and Twenty20s-since coming back had taken a toll on the swing bowler.
"I think it's very good for Pakistan as a team to chase this on the fifth day". We are a very young side, we had two debutant players, but we were very confident whatever the target will come, we will chase it down.
Ireland also had a chance to become the third team, after England and India, to win a Test after following on. That was as good as it got for Ireland.