set -v
pg_ctl stop
rm -rf $PGDATA
initdb --encoding=UTF8 --no-locale
mkdir $PGDATA/arc

cat <<@EOF >> $PGDATA/postgresql.conf
archive_mode = always
archive_command = 'test ! -f arc/%f && cp %p arc/%f'

restore_command = 'cp arc/%f %p'
recovery_target_timeline = 'latest'
@EOF

touch $PGDATA/standby.signal
pg_ctl start
sleep 3
pg_ctl promote
sleep 3
psql -c "create table test (a int);"
# These are the trigger for archive_command
psql -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # OK
psql -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # OK
psql -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # OK

sleep 1

touch $PGDATA/standby.signal
pg_ctl stop
pg_ctl start
echo "---- NG ---- (If we use archive_mode=on, archive_command is successful)"
sleep 10
pg_ctl promote
sleep 3
# These are the trigger for archive_command
psql -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # NG: archive_command failed
psql -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # NG: archive_command failed
psql -c "insert into test values (1); checkpoint; select pg_switch_wal();"  # NG: archive_command failed
