#!/bin/bash
#
# Ver. 1.3
# date: 17-01-2023
# upgrade ddns.txt file from multiple location
#
# lftp
# curl
# dig (dnsutils)

# sftp version 

function file_rotate () {
touch  $2
ROTATE_ROW=$1
ROW_COUNT=$(cat $2   | wc -l)
        if [ $ROW_COUNT -ge $ROTATE_ROW ]; then
                rm -fr  $2
                touch  $2
        fi
}

NAME=$HOSTNAME
DATE=$(date +"%Y-%m-%d %T")

# Check method list
WANIP_CHECK1=$(dig +short myip.opendns.com @resolver1.opendns.com)
WANIP_CHECK2=$(curl -0 --silent http://checkip.dyndns.it | awk '{print $6}' | cut -f 1 -d "<")


# --- CHANGE SETTING --- #
#Set default check method
WANIP=$WANIP_CHECK1

#Set ddns file log
TXT_FILE=ddns.txt
LOCAL_FULL_FILE=/tmp/$TXT_FILE


# Set ftp auth
FTP_USER="user"
FTP_PASS="pass"
FTP_HOST="host.local"
FTP_REMOTE_PATH="/opt/busybox_www/ddns/"
FTP_PORT="22222"

# ---- end setting --- #


# Get and Put file on remote FTP (need lftp installed and specific protocol sftp or ftp or other)
# sftp need first connection for accept secure key exchange
#lftp -u $FTP_USER,$FTP_PASS  ftp://$FTP_HOST -p $FTP_PORT  -e "set ssl:check-hostname no; set xfer:clobber on; lcd /tmp/ ;cd $FTP_REMOTE_PATH; get $TXT_FILE; exit"
#file_rotate  50  $LOCAL_FULL_FILE
#echo "$WANIP - $DATE ($NAME)" >> $LOCAL_FULL_FILE
#lftp -u $FTP_USER,$FTP_PASS  ftp://$FTP_HOST -p $FTP_PORT  -e "set ssl:check-hostname no; cd $FTP_REMOTE_PATH; put $LOCAL_FULL_FILE; exit"


# Get and Put file on remote SFTP (need lftp installed and specific protocol sftp or ftp or other)
# sftp need first connection for accept secure key exchange
lftp -u $FTP_USER,$FTP_PASS  sftp://$FTP_HOST -p $FTP_PORT  -e "set xfer:clobber on; lcd /tmp/ ;cd $FTP_REMOTE_PATH; get $TXT_FILE; exit"
file_rotate  50  $LOCAL_FULL_FILE
echo "$WANIP - $DATE ($NAME)" >> $LOCAL_FULL_FILE
lftp -u $FTP_USER,$FTP_PASS  sftp://$FTP_HOST -p $FTP_PORT  -e "cd $FTP_REMOTE_PATH; put $LOCAL_FULL_FILE; exit"
