#!/usr/bin/bash
# Copyright 2018-2023 Chad Lemmen http://www.lemmen.com
#
################################################################################
# File:     ifx2pg 
# Date:     2018-12-17
# Author:   Chad Lemmen http://www.stansoft.org
# Purpose:  Remove the trailing delimiter from an Informix unload file
#           for copy into a PostgreSQL database.
#
# History:  2023-10-27 - Remove the specified serial column position.
#
################################################################################

file=$1
sercol=$2

fix_tail() {
  in=$(cat $1)
  # Remove trailing delimiter
  sed -e 's/|$//' <<<"$in"
}

fix_serial() {
  in=$(cat $1)
  # Remove the serial column, using 'default' does not work with a copy
  sed -e "s/[^|]*|//$sercol" <<<"$in"
}

verify_file() {
  if ! [ -f "$file" ]; then
    echo "File '$file' not found."
    exit 1
  fi
}

case "$#" in
  1)
    verify_file
    fix_tail "$file"
    ;;
  2)
    verify_file
    fix_serial "$file" | fix_tail
    ;;
  *)
    echo "Usage: $0 [serial column num] <filename>"
    exit 1
    ;;
esac

