#!/macports/bin/bash

#
#   ${1} :: type of conversion (hard|soft) (default:soft)
#   ${2} :: old version of Perl5 (default: 12)
#   ${3} :: new version of Perl5 (default: 16)
#

declare type=${1:-soft}
declare -i versionOld=${2:-12}
declare -v versionNew=${3:-16}

declare -i counter=0
declare -i totalPorts=$( port -q list | wc -l )
declare -i portrev

#
# this time we're only interested in perl5.12
#
declare -i version=12

#
# find all the ports that are dependent on perl5.${version}
# or p5.${version}-<something>
#
while read portname[0] portname[1] portname[2]
do
    (( counter++ ))
    printf "\r[ %5i | %5i ] %-50s" ${counter} ${totalPorts} ${portname[2]}
    fundet=$( \
        grep -E -e "(perl5.${version}|p5.${version})" $(port file ${portname[0]}) \
    |   wc -l )
    if [ ${fundet} -gt 0 ]
    then
        cd  $(dirname $(port file ${portname[0]}))
        echo ''

        #
        # splice the PortGroup command into the Portfile
        #
        portrev=$( grep -i "PortGroup.*perl5" 'Portfile' | wc -l )
        if [ ${portrev} -eq 0 ]
        then
            mv  'Portfile' 'Portfile.orig'
            sed -En -e "1,/^PortSystem/p" 'Portfile.orig' \
                >  'Portfile'
            echo -e "PortGroup        perl5  1.0" \
                >> 'Portfile'
            sed -E  -e "1,/^PortSystem/d" 'Portfile.orig' \
                >> 'Portfile'
            rm  'Portfile.orig'
        fi

        #
        # replace the hardcoded values
        #
        case ${type} in
        ( 'soft' )
            sed -i '' -E \
                -e "/^\#/!s/perl5.${versionOld}/perl\$\{perl5.major\}/g" \
                -e "/^\#/!s/p5.${versionOld}/p\$\{perl5.major\}/g" \
                'Portfile'
        ;;
        ( 'hard' )
        ;;
            sed -i '' -E \
                -e "/^\#/!s/perl5.${versionOld}/perl5.${versionNew}/g" \
                -e "/^\#/!s/p5.${versionOld}/p/5.${versionNew}g" \
                'Portfile'
        esac
    fi
done < <( port list )
printf "\r[ %5i | %5i ] %-50s\n" ${counter} ${totalPorts} '*** FINISHED ***'
